Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Form : Select an entity or add a new one

Tags:

I have an order and a client entity.

I am wondering if it's possible with the actual Symfony2 form system to create an order form which will allow to:

  1. Select several clients from a dropdown (mix of collection and entity form type)
  2. And to create new clients on the fly (the default way for the collection type) if not in the dropdown list.

I've seen some way to do it by creating multiple forms in the same page, but this is not the way I would like to achieve it.

Are there any better ways to do this?

like image 632
Simon Taisne Avatar asked Apr 17 '12 15:04

Simon Taisne


2 Answers

I had a similar problem which may lead to your resolution:

I have a Category and Item relationship (Many-to-One) and I wanted to either select an existing item or create a new item.

In my Form class:

    $builder->add('item', 'entity', array(
        'label' => 'Item',
        'class' => 'ExampleItemBundle:Item',
    ));

    $builder->add('itemNew', new EmbedItemForm(), array(
        'required' => FALSE,
        'mapped' => FALSE,
        'property_path' => 'item',
    ));

    $builder->addEventListener(FormEvents::PRE_SUBMIT, function(FormEvent $event) {
        $data = $event->getData();
        $form = $event->getForm();

        if (!empty($data['itemNew']['name'])) {
            $form->remove('item');

            $form->add('itemNew', new EmbedItemForm(), array(
                'required' => TRUE,
                'mapped' => TRUE,
                'property_path' => 'item',
            ));
        }
    }); 
like image 126
Patrick Avatar answered Oct 13 '22 00:10

Patrick


You can map two fields in a form to the same property using the property_path option. Then, using form events, use the submitted data to make a decision and modify the form so that only one of the fields has a mapped option that is true.

like image 31
antony Avatar answered Oct 13 '22 00:10

antony