Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't access global variable from query builder function in form type

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?

like image 897
blahblah Avatar asked Aug 31 '26 14:08

blahblah


1 Answers

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

like image 129
Cerad Avatar answered Sep 02 '26 03:09

Cerad