无法从表单类型的查询构建器函数访问全局变量

时间:2017-01-20 11:20:40

标签: php symfony doctrine-orm symfony-forms query-builder

我正在尝试在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函数中的任何位置访问的全局变量?

2 个答案:

答案 0 :(得分:5)

问题是你需要显式指定传递给闭包的变量(也就是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

答案 1 :(得分:1)

听起来你并没有将参数传递给表单构建器 如果您在dump($options)函数中buildForm,您是否看到它们通过了?

要将自定义值添加到您的表单类型应该是的选项中;

<?php

// src/AppBundle/Form/Enitiy/PageType.php

namespace AppBundle\Form\Entity;

use Symfony\Component\Form\AbstractType,
    Symfony\Component\Form\FormBuilderInterface,
    Symfony\Component\OptionsResolver\OptionsResolver;

class PageType extends AbstractType
{

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('title');
    // ...
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Page',
            'parentPage' => false,
            'impact' => false
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'appbundle_page;
    }

}

然后你的控制器动作就像是;

$form = $this->createForm(new PageType(), $page, [
            'parentPage' => 'foo',
            'impact' => 'bar'
        ]);