I have an EntityType in my form and I would like set a default selected value, it's possible ?
This is my code in my FormType :
->add('pays', EntityType::class, [
'class' => Pays::class,
'choice_label' => function (Pays $pays) {
return $pays->getNomFrFr();
},
])
The value of each option of the select in HTML match with the id in my database :
<label for="boutique_pays" class="required">Pays</label><select id="boutique_pays" name="boutique[pays]">
<option value="1">Afghanistan</option>
<option value="2">Albanie</option>
<option value="3">Antarctique</option>
<option value="4">Algérie</option>
...
<option value="237">Wallis et Futuna</option>
<option value="238">Samoa</option>
<option value="239">Yémen</option>
<option value="240">Serbie-et-Monténégro</option>
<option value="241">Zambie</option>
</select>
I would like set the selected value to '75' (France), it's possible ?
Thanks in advance
Pass EntityManager and your default choice objectID when create form type.
$repository = $this->getDoctrine()->getRepository(YourClass)->find($id);
$yourDefaultValue = $repository->getId();
$form = $this->createForm(new YourTypeType($entityManager), $yourEntity, array(
'action' => $this->generateUrl('route_create'),
'method' => 'POST',
'your_default_value' => $yourDefaultValue,
));
add constructor in your form type.then replace your code...
private $em;
public function __construct($em) {
$this->em = $em;
}
->add('pays', EntityType::class, [
'class' => Pays::class,
'choice_label' => function (Pays $pays) {
return $pays->getNomFrFr();
},
'data'=>$this->em->getReference("YourEntity",$options['your_default_value'])
])
and finally, add your_default_value empty array in your setDefaultOptions
public function setDefaultOptions(OptionsResolverInterface
$resolver)
{
$resolver->setDefaults(array(
'data_class' => 'YourEntity',
'your_default_value' => array()
));
}