我有一个带有 1 个 EntityType 字段的表单,该字段必须包含取决于第二个 EntityType 字段的选项,该字段未映射到第一个实体中,如下所示:
服务类型.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
))
有人知道如何获取这些数据吗?或者如何通过另一种方式动态过滤选项?
感谢您的帮助!
最佳答案
您可以使用 jquery 来完成图书馆更简单一点:
首先,我们稍微更改构建器以将地点类型 id 渲染为 <option data-type="...">
使用 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>
关于javascript - Symfony - FormType - 动态选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39400337/