Symfony2 表单:创建新的或 select 现有的
Symfony2 Forms: create new or select existing
我有实体 A,它将 oneToMany 与实体 B 相关联。
我希望用户可以选择从现有的 B 实体中进行选择,或者在 A 类型的表单上创建一个新实体。到目前为止,我的表单上有这个:
->add('ExistingB', 'entity', array(
'class' => 'AppBundle\Entity\B',
'required' => false,
'property_path' => 'B',
'mapped' => false,
))
->add('newB', new BType(), array(
'required' => false,
'property_path' => 'B',
'mapped' => false,
));
$builder->addEventListener(
FormEvents::POST_SUBMIT , function (FormEvent $event) {
$formB= $event->getForm()->get('newB');
if ($formB->get('name')->getData() != null){
//here I need to somehow say to the form that it needs to set mapped true
//to the formB field so it can create a new entity and update the relationship
}else{
//here I need to do the same but with the ExistingB field
}
}
);`
我找不到如何更改映射属性,而且我得到它的时候,它并没有创建实体。我想那是因为在 post_submit 事件中更改字段为时已晚,因为数据已经下载到 A 实体。
但是..如果我使用 pre_submit 事件,那么我无法获取子 formB 的数据,因为当我请求它时它总是给我 null。
所以...我的大错误在哪里?
有人可以告诉我另一种方法来处理 symfony2 表单中的新功能或现有功能。我真的无法相信实现如此普遍的行为会如此困难。
我有实体 A,它将 oneToMany 与实体 B 相关联。 我希望用户可以选择从现有的 B 实体中进行选择,或者在 A 类型的表单上创建一个新实体。到目前为止,我的表单上有这个:
->add('ExistingB', 'entity', array(
'class' => 'AppBundle\Entity\B',
'required' => false,
'property_path' => 'B',
'mapped' => false,
))
->add('newB', new BType(), array(
'required' => false,
'property_path' => 'B',
'mapped' => false,
));
$builder->addEventListener(
FormEvents::POST_SUBMIT , function (FormEvent $event) {
$formB= $event->getForm()->get('newB');
if ($formB->get('name')->getData() != null){
//here I need to somehow say to the form that it needs to set mapped true
//to the formB field so it can create a new entity and update the relationship
}else{
//here I need to do the same but with the ExistingB field
}
}
);`
我找不到如何更改映射属性,而且我得到它的时候,它并没有创建实体。我想那是因为在 post_submit 事件中更改字段为时已晚,因为数据已经下载到 A 实体。
但是..如果我使用 pre_submit 事件,那么我无法获取子 formB 的数据,因为当我请求它时它总是给我 null。
所以...我的大错误在哪里?
有人可以告诉我另一种方法来处理 symfony2 表单中的新功能或现有功能。我真的无法相信实现如此普遍的行为会如此困难。