我正在尝试在Form类型中将参数设置为查询构建器.我想将影响变量设置为表单字段查询构建器.我从表单选项中获得了影响
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('title');
$parentPage = $options["parentPage"];
$impact = $options["impact"];
if($parentPage != null){
$builder->add('parent', 'entity', array(
'class' => "CoreBundle:Page",
'choices' => array($parentPage)
));
}else{
$builder->add('parent', 'entity', array(
'class' => "CoreBundle:Page",
'query_builder' => function(PageRepository $pr){
$qb = $pr->createQueryBuilder('p');
$qb->where("p.fullPath NOT LIKE '/deleted%'");
$qb->andWhere('p.impact = :impact')
->setParameter('impact', $impact);
return $qb;
},
));
}
为什么这段代码显示错误,它说$impact是未定义的变量.是不是可以从buildForm函数中的任何位置访问的全局变量?
解决方法:
问题是你需要显式指定传递给闭包的变量(也就是query_builder函数):
$builder->add('parent', 'entity', array(
'class' => "CoreBundle:Page",
'query_builder' => function(PageRepository $pr) use ($impact) { // ADD
$qb = $pr->createQueryBuilder('p');
$qb->where("p.fullPath NOT LIKE '/deleted%'");
$qb->andWhere('p.impact = :impact')
->setParameter('impact', $impact);
return $qb;
},
));
标签:doctrine-orm,query-builder,php,symfony,symfony-forms
来源: https://codeday.me/bug/20190823/1701649.html