I am trying to set parameter to query builder in Form type. I want to set impact variable to form field query builder. I get impact from form options
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;
},
));
}
Why this code is shown to be wrong, it says that $impact is undefined variable. Isn't it global variable that can be accessed from anywhere in the buildForm function?
The problem is that you need to explicitly specify variables passed to a closure (aka the query_builder function):
$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;
},
));
Most languages don't need this but php does. See example 3 : http://php.net/manual/en/functions.anonymous.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With