In my FormType class I have this in the buildForm method:
//...
->add('businessUnit', 'entity', array(
'class' => 'TrainingBundle:Employee',
'attr' => array('class' => 'form-control select2'),
'property' => 'businessUnit',
'empty_value' => 'All Business Units',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('e')
->groupBy('e.businessUnit')
->orderBy('e.businessUnit', 'ASC')
;
},
'required' => false
//...
This works fine, except instead of the "businessUnit" being put in the value of the <option> tags I get the employee ID. What I need is a dropdown with all distinct businessUnits in the Employee class. Perhaps I should be using choice instead of entity , but then I am not sure how to generate the array of choices.
ANSWER As described in the accepted answer I make this function
private function fillBusinessUnit() {
$er = $this->em->getRepository('TrainingBundle:Employee');
$results = $er->createQueryBuilder('e')
->groupBy('e.businessUnit')
->orderBy('e.businessUnit', 'ASC')
->getQuery()
->getResult()
;
$businessUnit = array();
foreach($results as $bu){
$businessUnit[$bu->getBusinessUnit()] = $bu->getBusinessUnit();
}
return $businessUnit;
}
Had to pass in the EntityManager to the form. And also put
use Doctrine\ORM\EntityManager; at top of the form