Symfony2 Form Builder - creating an array of choices from a DB query

后端 未结 1 1894
一整个雨季
一整个雨季 2021-01-01 03:20

In my FormType class I have this in the buildForm method:

//...
->add(\'businessUnit\', \'entity\', array(
                \'class\' => \'TrainingBundl         


        
相关标签:
1条回答
  • 2021-01-01 04:23

    Use choice instead. It has to be set with an array, so create a method to do it.

    ->add("type", "choice",
          array("label" => "Type",
                "choices" => $this->fillBusinessUnit(),
                "attr" => array("class" => "form-control select2"), 
                "empty_value" => 'All Business Units'))
    

    In this method you just have to run your query with the QueryBuilder, then loop the results, fill an array and return it.

    private function fillBusinessUnit() {
    
        $results = $er->createQueryBuilder('e')
                   ->groupBy('e.businessUnit')
                   ->orderBy('e.businessUnit', 'ASC');
    
        $businessUnit = array();
        foreach($results as $bu){
             $businessUnit[] = array("id" => $bu->getId(), "name" => $bu->getName()); // and so on..
        }
    
        return $businessUnit;
    }
    

    EDIT

    I guess you instantiate your Type in a Controller so you can pass it in the Type construct:

    $em = $this->getDoctrine()->getEntityManager();
    $form = $this->createForm(new YourType($em));
    

    then in your form class YourType.php:

    class YourType extends AbstractType {
    
        private $em;
    
        public function __construct(EntityManager $em){
            $this->em = $em;
        }
    }
    

    hope this helps :)

    0 讨论(0)
提交回复
热议问题