繁体   English   中英

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

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

在我的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
//...

这样可以正常工作,除了将“businessUnit”放在<option>标签的值中,我获得了员工ID。 我需要的是一个包含Employee类中所有不同businessUnit的下拉列表。 也许我应该使用choice而不是entity ,但后来我不确定如何生成选择数组。

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

 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; 在表格的顶部

请改用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;
    }
}

希望这可以帮助 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM