我正在尝试将参数设置为表单类型的查询生成器。我想设置 impact
变量以形成字段查询生成器。我从表单选项中获得影响
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); <-'Undefined variable $impact'
return $qb;
},
));
}
为什么这段代码显示是错误的,它说 $impact
是 undefined variable 。不是可以在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); <-'Undefined variable $impact'
return $qb;
},
));
大多数语言不需要这个,但 php 需要。 参见示例 3:http://php.net/manual/en/functions.anonymous.php
关于php - 无法从表单类型的查询构建器函数访问全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41762450/