我正在使用Symfony 2.7,并基于Symfonys EntityType
创建了一个自定义FormType。在此类型的FormEvents :: POST_SUBMIT中,我通过添加特殊实体来更新接收的数据。但是,这个机会不会发送回控制器:
控制器内的操作:
public function customEditAction(Request $request) {
$formData = $this->getFormData();
// formData has a property myEntities which is array of MyEntity
$form = $this->createForm('my_form_type', $formData);
$form->handleRequest($request);
if ($form->isValid()) {
foreach ($formData->getMyEntities() as $myEntity)
dump($myEntity);
}
...
}
my_form_type
class MyFormType extends AbstractType {
...
public function getName() {
return 'my_form_type';
}
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('myEntities', 'my_entities_type', array(
...
),
));
...
}
}
my_entities_type
class MyEntitiesType extends AbstractType {
...
public function getParent() {
return 'entity';
}
public function getName() {
return 'my_entities_type';
}
public function buildView(FormView $view, FormInterface $form, array $options) {
...
}
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use ($options) {
// Update data with a special entity.
$data = $event->getData();
$specialEntity = $this->getSomeSpecialEntity();
$data[] = $specialEntity;
// Dump shows, that the entiy was correctly added to $data
foreach ($data as $myEntity)
dump($myEntity);
$event->setData($data);
}
...
}
}
预期结果:
$formData->getMyEntities()
EntityType
(MyEntitiesType
的父级)获取所有可用实体以构建选择。 $formData->getMyEntities()
中的实体已预先选定Entity1
和Entity2
FormEvents::POST_SUBMIT
$specialEntity
中添加了数据/选择POST_SUBMIT
内和控制器内)都应显示所选实体,包括$ specialEntity 在第6步之后一切正常:虽然POST_SUBMIT
中的转储显示$specialEntity
在$ data中,但控制器内的转储仅显示用户选择的实体。 ..
为什么未将更改的数据提交回控制器?我需要做什么才能将更新的数据提供给控制器?
修改
在FormEvents::SUBMIT
中添加特殊实体不起作用,因为此实体未受管理,因此会在EntityType
实现中导致异常。