Symfony2 form entity field different beahviour

80 Views Asked by At

I'm using Symfony2 since few months. I'm able to accomplish basic operations such CRUD, etc. However I'm facing an issue now, regarding a two-entity form behaviour. I've got a unique form where there're 2 entities connected to 2 different tables:

  • guests
  • email suggested by guests

where every email_id is a foreign key into the guest row. Every guest may have no emails, than a null foreign key for that particular row.

Once the form has been sent by the user, it will be saved a new record into the guest table but I'd like that the field email (belonging to another entity) would be saved into a different table and performing some checks:

  • if the email is present into the table it should't be saved but I need to take its id and save it as foreign key into the new guest row;
  • if the email isn't into the table, then it has to be saved and connected to the new guest;
  • if the guest doesn't fill any email, then a null foreign key has to be put against the guest and no record will be saved into the email table.

I found many articles about entity-form CRUD operations but few or nothing about how to customise insert/update at one time according to a specific field in Symfony2.

Please can someone explains me how to do it or if there's somebody who knows articles/examples for, please, can he reports to me those articles?

This is a snippet of the form:

class InYourMindType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('title', 'text', array(
            'label' => 'label_think_title',
            'required' => true,
            'attr' => array(
                'title' => 'label_think_title',
                'class' => 'form-control'
            )
        ))->add('thinkFriend',
                new InYourMindFriendType

where new InYourMindFriendTypeis the email. Below the controller's snippet instead. At the moment just a simple method which saves the form

function sendInYourMindAction(Request $request)
{
    $EnForm = new InYourMind;

    $form = $this->createForm(new InYourMindType, $EnForm);

    if ($request->getMethod() === 'POST') {
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()
                    ->getEntityManager();
            $em->merge($EnForm);
            $em->flush();

            $this->get('session')
                    ->getFlashBag()
                    ->set('think-success-notice', 'message successfully sent');

            return $this->redirect($this->generateUrl('commonMainBundle_homepage'));
        }
    }


    return 'something';

} 
0

There are 0 best solutions below