1
votes

I am using an EntityType in a formType in Symfony 3. When I am displayed it in a new form all works great, the choicetype liste contain all the values from my database. But when I load existing data from my database the choice list don't load the value from the database, it display the placeholer. I have checked in the database and the value is saved. My form looks like this

->add('tester', EntityType::class, array(
                'class' => 'MyBundle:TesterList',
                'query_builder' => function (EntityRepository $er) {
                    return $er->createQueryBuilder('u')
                    ->orderBy('u.name', 'ASC');
                },
                'choice_label' => 'name',
                'choice_value' => 'name',
                'required' => true,
                'placeholder' => 'Select a tester',
                ))

For testing I try to change the EntityType to a ChoiceType with a list of 2, it works perfectly. I don't know what the problem with EntityType is.

Edit : The field is displayed in my form like this :

 {{ form_label(formHydraulicTest.testHeader.tester,'Tester' | trans) }}
 {{ form_widget(formHydraulicTest.testHeader.tester) }} 

The entity TesterList don't have any relation with others Entities. It is just a list of name.

The EntityType return an TesterList object when I try to saved it, so I add this function in the TesterList Entity.

public function __toString() {
    return $this->name;
}

With this I saved only the name of the tester and not the link to the entity.

2
Please add some information about your TesterList entity and your Form. There is nothing wrong with this piece of code, so the problem must be somewhere else. - Stephan Vierkant

2 Answers

0
votes

The generic EntityRepository may not know which Entities to fetch by just creating a named QueryBuilder 'u'. You may need the actual TesterList Repository. So your code will look something like this:

->add('tester', EntityType::class, array(
                'class' => 'MyBundle:TesterList',
                'query_builder' => function (TesterListRepository $er) {
                    return $er->createQueryBuilder('u')
                              ->orderBy('u.name', 'ASC');
                },
                'choice_label' => 'name',
                'choice_value' => 'name',
                'required' => true,
                'placeholder' => 'Select a tester',
                ))

Of course, add TesterListRepository to your use statements at the top of the form class.

0
votes

I found a way to make it works, I just select the default value with twig. I have updated it like this

 {{ form_label(formHydraulicTest.testHeader.tester,'Tester' | trans) }}
                    {{ form_widget(formHydraulicTest.testHeader.tester, { value : formHydraulicTest.testHeader.vars.value.tester}) }} 

I am not sure it is the best way to solve my issue, but it works ;)