Symfony2 Form : Select an entity or add a new one
forms, symfony
Solution
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',
));
}
});
Problem
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: - Select several clients from a dropdown (mix of `collection` and `entity` form type) - 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?