我有一个包含1个EntityType字段的表单,该字段必须包含根据未在第一个实体中映射的第二个EntityType字段的选项,如下所示:
ServicePlaceType.php:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('placetype', EntityType::class, array(
"class" => "AppBundle:PlaceType",
"choice_label" => "place",
"mapped" => false
))
->add('idplace', EntityType::class, array(
"class" => "AppBundle:Place",
"choice_label" => "place"
))
->add('...');
表格
+---------+--------------+---------------+-----------+
| Service | ServicePlace | Place | PlaceType |
+---------+--------------+---------------+-----------+
| | id | | |
+---------+--------------+---------------+-----------+
| | idplace > | < id | |
+---------+--------------+---------------+-----------+
| id > | < idservice | idPlaceType > | < id |
+---------+--------------+---------------+-----------+
| service | | place | placetype |
+---------+--------------+---------------+-----------+
因此,当我选择一个PlaceType时,我希望Place select只显示idplacetype与PlaceType id匹配的地方。
我尝试在javascript中使用PlaceType选择上的onChange事件,根据PlaceType实际值过滤Place选项,但我不知道如何在formType中获取Place的PlaceType属性。 我试过那种东西,但它不起作用
->add('idplace', EntityType::class, array(
"class" => "AppBundle:Place",
"choice_label" => "place",
"attr" => array("placeType" => $this->getPlaceType()), // nor like that
))
->add('idplace', EntityType::class, array(
"class" => "AppBundle:Place",
"choice_label" => "place",
"attr" => array("placeType" => function ($place) {
return $place->getPlaceType();
}), // neither like that
))
有人知道如何获取这些数据吗?或者如何通过其他方式动态过滤选项?
感谢您的帮助!
答案 0 :(得分:2)
您可以使用jquery库更简单一点:
首先,我们更改构建器,使用<option data-type="...">
选项将地点类型ID呈现为choice_attr
:
$builder
->add('placetype', EntityType::class, array(
"class" => "AppBundle:PlaceType",
"mapped" => false
))
->add('idplace', EntityType::class, array(
"class" => "AppBundle:Place",
'choice_attr' => function ($place) {
// output: <option data-type="...">...</option>
return array('data-type' => $place->getPlaceType()->getId());
},
))
接下来,在你的模板中:
{# ... #}
{{ form(form) }}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
// when the 1st <select> was changed, then update the 2nd
// from current value and data-type option attribute.
$(document).on('change', '#form_placetype', function () {
var $idplace = $('#form_idplace'),
// current value
placetype = $(this).val(),
// select available options from current value
$available = $idplace.find('option[data-type="' + placetype + '"]');
// deselect when the 1st <select> has changed.
$idplace.val('');
// hide no available options from current value
$idplace.find('option').not($available).hide();
// show available options from current value
$available.show();
});
// Update 2nd <select> on page load.
$('#form_placetype').trigger('change');
</script>