How to use related select boxes in Symfony ?
Let\'s say, I have a select list containing compagnies and another containing employees of the selected company. How do I d
Concerning what you already tried, I think you should retry your first/second ideas:
My first idea was to use the form entity type, thinking the component could be binded somehow on another field. ie. update list of employees based on the value of the selected company.
You can populate the employees select box using the entity
type.
All you have to do is to define the good options:
class FooType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('employee', 'entity', array(
'class' => 'Entity\Employee',
'query_builder' => function ($repository) use($options) {
return $repository
->createQueryBuilder('e')
->where('e.company = :company')
->setParameter('company', $options['companyId'])
;
},
))
;
}
public function getDefaultOptions(array $options)
{
return array('data_class' => 'Entity\Foo', 'companyId' => null);
}
}
Then I thought about manually passing the selected company as parameter to the query builder of the second dropdown list.
The example here filters the employees list based on the companyId form's option. You can modify this behavior by filtering directly on the company present in the form's data.
public function buildForm(FormBuilder $builder, array $options)
{
$companyId = $builder->getData()->getCompanyId();
$builder
->add('employee', 'entity', array(
'class' => 'Entity\Employee',
'query_builder' => function ($repository) use ($companyId) {
return $repository
->createQueryBuilder('e')
->where('e.company = :company')
->setParameter('company', $companyId)
;
},
))
;
}
You still have to implement the getEmployee()
and setEmployee()
methods in your Entity\Foo
class.
But when the form is created, the values are empty. The values are only set on bindRequest.
No. Values are set when you create you form using form factory (third argument),
OR when you call $form->setData($foo);
. Data is modified when you bind
new inputs to the form.
There could be a problem with this approach: it's possible that the employee id bound to the form is not available in the form choice list, because you changed the company (and thus the employees).