我正在尝试在Form类型中将参数设置为查询构建器.我想将impact
变量设置为表单字段查询构建器.我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
是未定义的变量.是不是可以从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