我正在使用两个EntityType类型字段。第二个字段中的数据取决于第一个字段中的选择。来自第三个字段的数据取决于第二个字段中的选择。如何从动态开始并将选择值从第一个字段传递到第二个字段?现在我想出来:
->add('country', EntityType::class, [
'class' => 'AppBundle:Country',
'choice_label' => 'name',
'label' => 'Country',
'data' => $countryId //this is wrong, i know. here i must somehow save the choice and pass it into next field
])
->add('state', EntityType::class, [
'class' => 'AppBundle:State',
'query_builder' => function (EntityRepository $er) use ($countryId) {
return $er->createQueryBuilder('s')
->where('s.country =:country_id')
->setParameter('country_id', $countryId)
->orderBy('s.name', 'ASC');
},
'choice_label' => 'name',
'label' => 'State',
'data' => $stateId //this is wrong, i know. here i must somehow save the choice and pass it into next field
])
->add('city', EntityType::class, [
'class' => 'AppBundle:City',
'query_builder' => function (EntityRepository $er) use ($stateId) {
return $er->createQueryBuilder('c')
->where('c.state =:state_id')
->setParameter('state_id', $stateId)
->orderBy('s.name', 'ASC');
},
'choice_label' => 'name',
'label' => 'City'
])
我使用文档,我来到这段代码。我收到错误:“你不能将子项添加到一个简单的表单中。也许你应该将选项”compound“设置为true?”。我尝试使用返回'触发器'来强化getParent方法,但它无法加载该类。我怎样才能正确地提升它?
$formModifier = function (FormInterface $form, PowerPlant $power_plant = null) {
$devices = null === $power_plant ? array() : $power_plant->getDevices();
$form->add('device', EntityType::class, [
'class' => 'AppBundle:Device',
'placeholder' => '',
'choices' => $devices,
'label' => 'Device',
]);
};
->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifier) {
$data = $event->getData();
$formModifier($form = $event->getForm(), $power_plant = $data->getPowerPlant());
}
)
->get('power_plant')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier) {
$power_plant = $event->getForm()->getData();
$formModifier($event->getForm()->getParent(), $power_plant);
}
)
在我的模板中,我添加了JS:
<script>
var $power_plant = $('#trigger_power_plant');
$power_plant.change(function() {
var $form = $(this).closest('form');
var data = {};
data[$power_plant.attr('name')] = $power_plant.val();
$.ajax({
url : $form.attr('action'),
type: $form.attr('method'),
data : data,
success: function(html) {
$('#trigger_device').replaceWith(
$(html).find('#trigger_device')
);
}
});
});