Select existing entity or create a new one - php

I've read Symfony 2 Entity field type with select and/or add new and this Symfony2 Form : Select an entity or add a new one but those topics didn't solve what I want.
I want for user to choose from existing entities but if he wants to, should be able to create a new one after clicking on a button ( which will render form ). I know how to render entities in select, I know how to render field which allows user to create few new entities ( collection ) but I don't know how to render both of them together.
right now I have select:
->add('place', 'entity', array(
'required' => false,
'class' => 'MyBundle\Entity\Place',
))
but as I said - I want to allow user to add new entity if he wants to. I was trying with collection:
->add('place', 'collection', array(
'required' => false,
'data' => [new Place()],
'type' => new \MyBundle\Form\Place\PlaceType(),
'allow_add' => true,
'options' => array( 'label' => false),
))
but that only allowed user to create new entities, not to select from existing ones...

If you want them to be able to add a new entity and select an existing one i'd suggest you take a look at form events.
http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html

Related

Symfony form CollectionType remove empty value

I'm using Symfony 3.3 and I have a form with a CollectionType like :
$builder->add('links', CollectionType::class, array(
'label' => false,
'entry_type' => LinkType::class,
'entry_options' => ['data_class' => CompanyLink::class],
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'by_reference' => false,
));
I followed the documentation : https://symfony.com/doc/current/reference/forms/types/collection.html
This is what I have in my view :
So, the form displays well data already in my database (one line each time) but it always adds an empty field in addition.
How can I remove this empty field? Because I want to have this line only I click on the button "Ajouter".
Thanks!
I think in your function of rendering form you have setData(),
to render the form without data, you just need to do this sample:
//Your main entity
$mainEntity = new Entity();
//adding the other entity into collection variable of other entity of main entity
$mainEntity->addOtherEntity(new otherEntity());
$form = $this->createForm(
MainEntityForm::class,
$mainEntity
);
hope it helps.
This post is a bit old ihope it's not to late. I found a solution, even if you travel the collectionType field with a twig for.
To avoid having this empty field after your for loop, add
{% do form.your_field.setRendered %}
It worked for me, hope it will do the same for you :)

Symfony Sonata project: How to add multiple input texts to block?

I would like to add a collection of input text with same name (i.e. name="blabla[]") filed to admin block with add/delete buttons.
I'm using collection form field type but can't see add/delete buttons
public function buildEditForm(FormMapper $formMapper, BlockInterface $block)
{
$formMapper->add('settings', 'sonata_type_immutable_array', array(
'keys' => array(
array('title', 'collection',
array('type' => 'text' ,
'required' => true,
'allow_add' => true,
'data' => array('First' => 'One')
)
)
)
));
}
I get below result without add/delete buttons!
Any idea how to get it working ?
I think you should use sonata_type_collection or sonata_type_native_collection instead of collection.
Here is an extract of the field doc :
14.1.7. SONATA_TYPE_NATIVE_COLLECTION (PREVIOUSLY COLLECTION)
This bundle handle the native Symfony collection form type by adding:
an add button if you set the allow_add option to true. a delete button
if you set the allow_delete option to true.

other in entity choice list form

I'm new to symfony. I have a drop down in a form with data fetched from DB.
$builder->add('category', 'entity', array(
'label' => 'category',
'class' => 'MyBundle:category',
'expanded' => false,
'multiple' => false,
'mapped' => false,
'empty_value' => 'category'
));
$builder->add('other_category', 'text', array(
'label' => 'category',
'required' => false,
'invalid_message' => 'Please enter a valid category',
'mapped' => false,
));
the user can also add new category to the table. when other is selected from drop down, the 'other_category' input field is shown, else its hidden.
'Other' was added to drop down with the help of this code.
public function finishView(FormView $view, FormInterface $form, array $options)
{
$new_choice = new ChoiceView(array(), 'other', 'Other');
$view->children['category']->vars['choices'][] = $new_choice;
}
If a option is selected from drop down the form works fine. Data gets stored without any error. But if user selects 'other' and enters a new category the page reloads with 'This value is no valid' under the category options and there is no form validation for the 'other_category' entered by user.
Can someone help me with the form validation and also entering of a new category or suggest a better way to implement the above functionality.
The validation error is happening because the form field type is Entity, but there is no "MyBundle:category" entity with the identifying value "other".
You've not specified the "choice_label" property in your Entity form type so I'll assume your "MyBundle:category" entity has a __toString() function. This would mean none of the "MyBundle:category" entities return "other" in their __toString() function.
I can think of two options to work around this right now:
1) Add a "MyBundle:category" entity with value "other". This is the easiest way, but it's fairly assumed you don't want such a category to exist in your database.
2) Load the list of "MyBundle:category" entities in advance from your controller, build them into an associative array, append your "other" option to the array, then pass that array to the form. You'd need to swap the Entity form type for a Choice type and use the categories array as the choices.
If your form is a FormType class you'll need to pass the array in with the class constructor.
If you don't mind having a new category with an "other" value in your category table, just add it. Otherwise go for option 2, which won't make much difference to what you do after receiving the submitted form as this form field isn't mapped to an entity property anyway.

How to add dynamically-created sub-forms as a collection in Symfony/Silex FormBuilder?

I'm trying to dynamically generate a form based on user-provided field definitions. This is fairly straightforward for the basic form:
$builder = $app['form.factory']->createBuilder('form', $my_data);
foreach ($my_user_provided_field_definitions as $field) {
$builder->add($field->handle, $field->type, $field->options);
}
$form = $builder->getForm();
But I also want to have sub-forms using the collection field type, and while it is so easy to dynamically generate the top-level form as I've done above, it does not seem possible to dynamically generate a sub-form for the collection field because all of the docs and sample code I've come across utilize either a single field like so:
$builder->add('my field', 'collection', array(
'type' => 'text',
'allow_add' => true,
));
...or a custom "Type" object, like so:
$builer->add('my field', 'collection', array(
'type' => new TagType(),
'allow_add' => true,
));
The TagType class in the above example must be defined in code (see http://symfony.com/doc/master/cookbook/form/form_collections.html )... but my problem is that I cannot have the class defined in code because these sub-forms are dynamically generated based on user data -- so I do not know what fields the sub-form will contain until run-time!
Is there a way to dynamically generate the sub-forms that can then be passed in to the top-level form, or is this a use case that is not handled by the Symfony FormBuilder?

Symfony2 Form validation dependency between form_types in one form

In my symfony2 project I created a new FormType which is called "ChoiceAndOrTextType" which is a list of choices (checkboxes) but the user can also check the "others" option and write his answer into a textfield.
The code is like this one here in the answer of bschussek:
Use a conditional statement when creating a form
$builder
->add('choice', 'choice', array(
'choices' => $options['choices'] + array('Other' => 'Other'),
'required' => false,
))
->add('text', 'text', array(
'required' => false,
))
->addModelTransformer(new ValueToChoiceOrTextTransformer($options['choices']))
;
Now i want to validate this correctly, so when the user checks "Others" then the textfield needs to be filled out, if "Others" isn't checked it can be blank. (Kind of dependent validation).
How do I do this?
You need to use two validation constraints, for example in validation.yml yaml file

Categories