Symfony2表单:创建新的或选择现有的 [英] Symfony2 Forms: create new or select existing
问题描述
我有一个实体A,该实体将oneToMany与实体B相关联. 我希望用户可以选择从现有的B实体中进行选择,或者以A类型的形式创建一个新的实体.到目前为止,我的表单中已经包含以下内容:
I have and entity A which relates oneToMany with entity B. I want the user to have the option of selecting from existing B entities or create a new one on the form of type A. So far I have this on my form:
->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实体,所以对于字段的更改为时已晚.
I cant find how to change the mapped attribute, and the times I got it, it doesn't create the entity. I suppose that's because in the post_submit event its too late for changes on the fields since the data is already downloaded to the A entity.
但是..如果我使用pre_submit事件,那么我将无法获得子formB的数据,因为当我要求它时,它总是使我为null.
But.. if I use the pre_submit event, then I can't get the data of the child formB, since it always gives me null when I ask for it.
那么...我的大错误在哪里?
有人可以向我展示另一种以symfony2形式处理新功能或现有功能的方法.我真的不敢相信,实现如此常见的行为可能会如此困难.
So... where is my big mistake?
Somebody can show me another way to deal with new or existing feature in symfony2 forms. I really can't believe that it could be that hard to implement so common behavior.
推荐答案
您可以使用pre Submit事件,只需执行以下操作: https://github.com/LPodolski/selectOrCreateOptionForm/blob/master/src/AppBundle/Form/ItemType.php#L36
you can use pre submit event, you just have to do this like this: https://github.com/LPodolski/selectOrCreateOptionForm/blob/master/src/AppBundle/Form/ItemType.php#L36
完整的项目,演示其工作方式: https://github.com/LPodolski/selectOrCreateOptionForm
full project that demonstrates how this should work: https://github.com/LPodolski/selectOrCreateOptionForm
这篇关于Symfony2表单:创建新的或选择现有的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!