1

How can I set a default choice on Symfony's EntityType, to use when the bound form object does not have a value?

I've tried the following (suggested in this answer), but the data option overwrites even a bound value.

class FooEntityType extends AbstractType
{
    public function configureOptions(OptionsResolver $resolver)
    {
        ...
        $resolver->setDefaults([
            'choices' => $fooEntities,
            'class' => 'FooBundle:FooEntity',
            'choice_label' => 'name',
            'expanded' => true,
            'multiple' => false,
            'data' => $fooEntities[0],
        ]);
    }

    public function getParent()
    {
        return EntityType::class;
    }
}
Community
  • 1
  • 1
Jonathan
  • 13,947
  • 17
  • 94
  • 123
  • 1. Questions subject about Entity Type but you provide code sample for ChoiceType 2. please read documentation carefully http://symfony.com/doc/current/reference/forms/types/entity.html find docs for "data" attribute. it says "The data option overrides this default value" 3. please clarify your question – Denis Alimov Sep 28 '16 at 16:20
  • @DenisAlimov Oops! Some old code slipped in there. I've updated my question and to clarify, this is about the EntityType. – Jonathan Sep 28 '16 at 16:37
  • Yeah, read my second point. There is docs for "data" option :) – Denis Alimov Sep 28 '16 at 16:42
  • The docs for `data` confirm that my solution doesn't work, as they override the bound model. Unless I'm missing something? – Jonathan Sep 28 '16 at 16:51

2 Answers2

1
  1. you should move this code to buildForm(FormBuilderInterface $builder, array $options) method in your Type
  2. try this

    $entity = $options['data']; // this will be your entity
    
    // form builder
    $builder->add('entityProperty', EntityType::class, [
        'choices' => $fooEntities,
        'class' => 'FooBundle:FooEntity',
        'choice_label' => 'name',
        'expanded' => true,
        'multiple' => false,
        'data' => $entity->getEntityProperty() ? $entity->getEntityProperty() : $fooEntities[0]
    ]);
    
  3. Also you can solve this workaround by form events, but it does not worth it

Denis Alimov
  • 2,861
  • 1
  • 18
  • 38
0

Once you create the form, you should add the entity to that method (assuming you are in a controller):

# src/Controller/MainController.php
$entity = new Entity();
$entity->setCertainValue('choice-value');

$form = $this->createForm(EntityType::class, $entity);
$form->handleRequest($request);

if ($form->isValid()) {
    // Do something nice with the entity, data is filled here
}
Rvanlaak
  • 2,971
  • 20
  • 40
  • Thanks Rvanlaak. This is my current workaround, but it seems a shame to have to do it outside the type as I'd have to duplicate the entity fetching logic. The other form types have an option for a default value, so I was expecting one here. – Jonathan Sep 28 '16 at 17:49