【发布时间】:2016-05-25 08:01:23
【问题描述】:
我正在尝试关注http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html#cookbook-form-events-submitted-data的symfony2动态表单修改教程
我的架构与他们在教程中使用的架构有点不同。我的由以下关系组成:
国家(一对多)办事处
办公室(一对多)员工
当我编辑现有员工时,我希望它加载办公室所在的国家作为默认选项,除了在办公室下拉列表中仅显示该国家/地区内的办公室(除非选择了另一个国家,然后jQuery 代码(不包括在内)应该相应地改变)。
然而,结果;是 Country 字段仍然显示占位符值,而不是 Employee's 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(),
));
}
);
}
【问题讨论】:
标签: php symfony-forms symfony