Reputation: 361
I have an entity type form field in my Symfony2 project.
$builder = $this->createFormBuilder();
$projects = $this->getProjects();
$builder->add('project', 'entity',
array(
'class' => 'MyBundle:Project',
'required' => false,
'choices' => $projects,
));
The problem I'm having is, when the getProjects()
method will return an empty result set, the drop down list will have all the projects in the Project table.
Is there any way to disable this behavior?
Upvotes: 3
Views: 5763
Reputation: 4957
I believe the unexpected behaviour is occurring because you are mixing up the use of the Choice and Entity form field types.
You are specifying an Entity field (second parameter to $builder->add()) and then attempting to populate it with values using the 'choices' option. However, the 'choices' option is not directly applicable to the Entity field type, although it is said to inherit from Choice. Rather, an Entity field is intended to automatically load the choices from the database for you. If you set only the Entity 'class', the field is populated with all the entities from the table in ascending primary key order. In order to load a subset of entities and/or load them in a particular order you can set a 'query_builder' function.
For example, to create a drop-down list of all countries in ascending name order:
$builder->add('country',
'entity',
array('class' => 'My\Bundle\Entity\Country',
'property' => 'name',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('country')
->orderBy('country.name', 'ASC');
},
'required' => true,
'empty_value' => false));
The query can be as simple or complex as required. See Using Doctrine's Query Builder.
I suspect that the way the project field is created in the question causes the underlying choices for the drop-down to be set twice - firstly when the 'class' option is set, to all the available project entities, secondly when the 'choices' option is set, to the result of $this->getProjects(). Presumably if the latter is an empty array it does not override the former and thus all the projects appear in the list.
If for some reason you can't use a query builder to get the projects for the drop-down then you can use a Choice field type and map the projects data into the 'choices' option manually. For example, something like this:
$builder = $this->createFormBuilder();
$projects = $this->getProjects();
$projectChoices = array();
foreach ($projects as $project) {
$key = $project->getId();
$value = $project->getName();
$projectChoices[$key] = $value;
}
$builder->add('project',
'choice',
array('choices' => $projectChoices,
'required' => false));
Note that in this case the value of the 'project' field will be a Project id whereas for an Entity field it will be an actual Project entity, which is another reason why it is preferable to use an Entity field.
Upvotes: 6