Symfony2 Forms: create new or select existing

2020-07-21 03:18发布

问题:

I have and entity A wich 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
                }
         }
    );`

I cant find how to change the mapped atribute, and the times I got it, it doenst create the entity. I suppose thats becasuse in the post_submit event its too late for changes on the fields since the data is already downloaded to the A entity. Buuut.. if I use the pre_submit event, then I cant get the data of the child formB, since it always gives me null when I ask for it.

So... where is my big mistake? Somebody can show me another way to deal with new or existing feature in synfony2 forms. I really cant believe that it could be that hard to implement so common behavior.

Thanks so much in advance

回答1:

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

full project that demonstrates how this should work: https://github.com/LPodolski/selectOrCreateOptionForm



标签: forms symfony