Symfony2表单生成器 - 从数据库查询创建一系列选项

时间:2014-04-04 07:37:34

标签: php symfony

在我的FormType类中,我在buildForm方法中有这个:

//...
->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
//...

这样做很好,除了&#34; businessUnit&#34;被放入<option>标签的值我得到了员工ID。我需要的是一个包含Employee类中所有不同businessUnit的下拉列表。也许我应该使用choice而不是entity,但后来我不确定如何生成选择数组。

ANSWER 如接受的答案所述,我做了这个功能

 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;
    }

必须将EntityManager传递给表单。而且还说 表格顶部的use Doctrine\ORM\EntityManager;

1 个答案:

答案 0 :(得分:6)

请改用choice。它必须使用数组设置,因此请创建一个方法来执行此操作。

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

在此方法中,您只需使用QueryBuilder运行查询,然后循环结果,填充数组并将其返回。

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;
}

修改

我猜你在Controller中实例化你的Type,这样你就可以在Type构造中传递它:

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

然后在您的表单类YourType.php

class YourType extends AbstractType {

    private $em;

    public function __construct(EntityManager $em){
        $this->em = $em;
    }
}

希望这有助于:)