Symfony2 表单:创建新表单或选择现有表单

2024-03-17

我有一个实体 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 形式中的新功能或现有功能的方法。我真的不敢相信实施如此常见的行为竟然如此困难。


您可以使用预提交事件,只需这样做:https://github.com/LPodolski/selectOrCreateOptionForm/blob/master/src/AppBundle/Form/ItemType.php#L36 https://github.com/LPodolski/selectOrCreateOptionForm/blob/master/src/AppBundle/Form/ItemType.php#L36

演示其如何工作的完整项目:https://github.com/LPodolski/selectOrCreateOptionForm https://github.com/LPodolski/selectOrCreateOptionForm

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Symfony2 表单:创建新表单或选择现有表单 的相关文章

随机推荐