gpt4 book ai didi

php - Symfony2 Form Builder - 从数据库查询中创建一系列选择

转载 作者:可可西里 更新时间:2023-11-01 14:02:50 25 4
gpt4 key购买 nike

在我的 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 类中所有不同 businessUnits 的下拉列表。也许我应该使用 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;在表单顶部

最佳答案

改用选择。它必须用一个数组来设置,所以创建一个方法来完成它。

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

希望这有帮助:)

关于php - Symfony2 Form Builder - 从数据库查询中创建一系列选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22856476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com