Symfony EntityType required empty option - php

I'm trying to create a dropdown list (EntityType) with the selection required but allow an option which maps to null.
In other words there is a list of entities in a drop down list and an additional option that maps to null and the user has to click on the list to select one.
I can try the following code, but the problem is that the user is not required to click on the drop down to select the option that maps to null labelled 'Other':
$choices = $em->getRepository(Instrument::class)->findAll();
$choices[] = ['Other' => null];
$form->add('instrument', EntityType::class, [
'placeholder' => 'Other',
'class' => Instrument::class,
'required' => true,
'choices' => $choices,
]);
Is there anyway to set the selection required with an option that maps to null?

Yes, you can set the 'required' option to true and still allow for a null option in the dropdown. You can use a placeholder to display the text for the null option and add a validation constraint to check if the selected value is not null.
Example:
$choices = $em->getRepository(Instrument::class)->findAll();
$choices[] = ['Other' => null];
$form->add('instrument', EntityType::class, [
'placeholder' => 'Please select an option or Other',
'class' => Instrument::class,
'required' => true,
'choices' => $choices,
'constraints' => [
new NotNull([
'message' => 'Please select an option or Other'
])
],
]);

Related

add option to select tag for EntityType field before creating the form

I have a form containing two EntityType fields, first one is category and the second is subCategory, the category field will have all the categories that i have in the database, but i want to add one more to these, which is "all categories", and i want it to be the one selected by default, how can i achieve this..
$builder
->add(
'category',
EntityType::class,
[
'label' => 'Catégorie',
'class' => Category::class,
'choice_label' => 'title',
'mapped' => false
]
)
->add(
'subCategory',
EntityType::class,
[
'label' => 'Sous-catégorie',
'class' => SubCategory::class,
'choice_label' => 'title',
'mapped' => false
]
);
You can construct your array of choices manually and use ChoiceType, for example:
// retrieve list of your categories in your controller or somewhere else
// and pass it using the options. Add it also before the default option "All categories".
$categories = $options['categories'];
$builder->add('category', ChoiceType::class, [
'choices' => $categories,
...

symfony how get selected data from select

Entity Type is defined as follow in my form:
->add('esame_' . $i, EntityType::class, array(
'label' => false,
'mapped' => false,
'class' => 'AppBundle:Nome_esame',
'required' => true,
'multiple' => true,
'choice_label' => 'nome',
// 'disabled' => 'disabled',
'attr' => array(
'placeholder' => 'Esami',
'class' => 'max_width esame_row select_esame',
// 'class'=>'col-md-12 col-md-offset-0 col-xs-9 col-xs-offset-3 ',
)
))
In my form submit, I want to take all the selected value and create a new entity from every one.
I tried this:
foreach($form->get('esame_0')->getData() as $value){
$field= new Field();
$field->setvalue($value); // ->$value i want is the val of selected option
}
but $form->get('esame_0')->getData() does not return the selected data..
How can I do it?
The value that comes with EntityType is an Entity object. Try this way.
$entityObject = $form->get('esame_0')->getData()
$data = $entityObject->getId() or $entityObject->(Entity getter function)

How to set default country in Symfony3 form?

I'm using Symfony3 form. I have aCountryType in my Symfony form Builder. It's working correctly. But suppose the user belongs to a Company which is based in Spain. For that User I want to set the default country to be Spain and then show the rest of the countries. How can I do this in Symfony3.
I tried this but its not working.
$builder->add("country", CountryType::class, array(
"label" => "Country",
"required" => false,
"preferred_choices" => array(
"ES" => "Spain",
),
));
Thank you for your time.
In this type Country::class, for use the preferred selection on array you should use:
->add('country', CountryType::class, [
'preferred_choices' => ['DE'],
'label' => 'address.form.country.label',
'attr' => [
'class' => 'form-control',
'placeholder' => 'address.form.country.placeholder'
],
'label_attr' => [
'class' => 'col-sm-2 col-form-label'
],
])
You can use the data option to set the default country.
preferred_choices will put countries at the top of the list, but it will not set them as the default selected option.
This should be the way to go:
->add(
'Country',
CountryType::class,
[
'data' => 'ES',
'label' => 'Country',
]
)
(tested with Symfony 4 and 5)

Multi select dropdown CakePHP 3 selected issue

$selected_country = array(1,3);
$this->Form->input('country', [
'options' => $source_types,
'label' => 'Country: ',
'multiple' => true,
'class' => ' form-control',
'selected' => $selected_country,
'type' => 'select'
]);
If selected country has only one value then it selects the option but if the selected country has more than one value then it doesn't select any value.
If you want to pass more than one value on $selected_country, try it:
echo $this->Form->select('rooms', [
'multiple' => true,
// options with values 1 and 3 will be selected as default
'default' => [1, 3]
]);
Reference: CakePHP Cookbook
For anyone this works
echo $this->Form->input('venues._ids', ['options' => $venues, 'class'=>'form-control select4', 'label' => false]); IF you have the database associations set up AND you have it referenced in the controller like so
$event = $this->Events->get($id, [
'contain' => ['Venues']
]);
otherwise adding the 'default' => [1, 2] ids in also works but it has to be first created in the controller and then fed to the view in list form.

Adding dynamic elements to Symfony form on PRE_SUBMIT

I am trying to use Symfony Form Component with Silex framework at the moment. I added some fields in buildForm method of my form type class. Also user can click on a button and add unlimited textarea element using javascript on the frontend. Now on PRE_SUBMIT event, I do the following to add these fields to the form
$data = $event->getData();
$form = $event->getForm();
foreach ($data as $key => $value) {
if (stristr($key, '_tb_') !== false) {
$id = str_ireplace('_tb_', '', $key);
$form->add('_tb_' . $id, 'hidden');
$form->add('_title_' . $id, 'text', [
'required' => false,
'label' => 'Title',
'constraints' => [
new Length(['min' => 6]),
]
]);
$form->add('_img_url_' . $id, 'text', [
'required' => false,
'label' => 'Image Url',
'constraints' => [
new Url(),
]
]);
$form->add('_img_alt_' . $id, 'text', [
'required' => false,
'label' => 'Image Alt',
'constraints' => []
]);
$form->add('_content_' . $id, 'textarea', [
'required' => true,
'attr' => [
'data-role' => '_richeditor'
],
'constraints' => [
new Length(['min' => 100]),
]
]);
}
}
I can see these fields are added to the form and populated once the form is submitted for the first time but for some reason all the constraints are ignored only for these new added fields. Is there a way to force Form to honour the constraints for the newly added elements?
The form component and validation can be tricky. A easy misconception is that the form type option "required" will imply a NotBlank validation constraint. This is not the case, the docs explain that option to be "superficial and independent from validation" only concerned with form element rendering (HTML5 required attr, label, etc).
To make things trickier, that you are specifying a minimum length constraint, one might assume that no (or zero) length would be considered invalid. This is also not the case. The length validator is only concerned with non-null / non-empty values. :-/
So! Modifying the text area field to include NotBlank() should do the trick:
$form->add('_content_' . $id, 'textarea', [
'required' => true,
'attr' => [
'data-role' => '_richeditor'
],
'constraints' => [
new NotBlank(),
new Length(['min' => 100]),
]
]);

Categories