我正在尝试遵循http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html#cookbook-form-events-submitted-data上的symfony2动态表单修改教程
我的架构与他们在本教程中使用的架构有些不同。矿山包括以下关系:
国家(一对多)办公室
办公室(一对多)员工
当我编辑现有员工时,除了只在Office下拉列表中显示该国家/地区内的办公室(除非选择了另一个国家/地区,然后再使用jQuery代码)外,我希望它加载Office所在的国家/地区作为默认选项。 (不包括在内)应进行相应的更改)。
结果,但是;是“国家/地区”字段仍显示占位符值,而不是雇员办公室的正确国家/地区。(从好的方面来说,Office下拉列表仅显示该国家/地区的办公室,这意味着$ country-> getOffices()调用正在工作,因此我正在使用正确的Country对象,但似乎无法选择它默认)。
我是否遵循此处的最佳做法?我缺少什么让我不能在相关实体的表单中设置值的东西吗?
代码:
class EmployeeType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('country', EntityType::class, array(
'class' => 'AppBundle:Country',
'mapped' => false,
'placeholder' => '=== Select a Country ===',
))
;
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) {
$form = $event->getForm();
// This will be the Employee entity
$data = $event->getData();
$office = $data->getOffice();
$country = null === $office ? array() : $office->getCountry();
$form->get('country')->setData($country); // I think this is what's not working properly.
$form->add('office', EntityType::class, array(
'class' => 'AppBundle:Office',
'placeholder' => '=== Select an Office ===',
'choices' => $country->getOffices(),
));
}
);
}
我有机会快速阅读了您参考的教程链接,并且我认为您对错误发生的位置是正确的。
我认为(但不确定),这可能会解决:
$office = $data->getOffice();
$offices = null === $office ? array() : $office->getCountry()->getOffices();
$form->add('office', EntityType::class, array(
'class' => 'AppBundle:Office',
'placeholder' => '=== Select an Office ===',
'choices' => $offices,
));
我仅显示您需要更改的相关部分。试试看,看看是否有帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句