我无法在createFormBuilder中使用变量

时间:2016-07-03 14:52:44

标签: forms symfony-forms symfony

为什么我不能在我的函数createFormBuilder中使用我的变量$ idType?

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $idType = $options['data']->getEvenement()->getType()->getId();

    $builder
        ->add('depart',      DateTimeType::class, array(
            'widget' => 'single_text'
        ))
        ->add('inscription', TextType::class)
        ->add('prixNl',      IntegerType::class)
        ->add('prixL',       IntegerType::class)
        ->add('resultat',    TextType::class)
        ->add('sousType',     EntityType::class, array(
            'class'        => 'CalendrierBundle:SousType',
            'choice_label' => 'nom',
            'multiple'     => false,
            'query_builder' => function (EntityRepository $er) {
                return $er->createQueryBuilder('u')
                    ->where('u.typeId = :type')
                    ->setParameter('type', $idType);
            }
        ))
        ->add('save',        SubmitType::class)
    ;
}

她不认识

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

您应该使用use ($idType)关键字将$ idType变量从父作用域继承到closure

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $idType = $options['data']->getEvenement()->getType()->getId();

    $builder
        ->add('depart',      DateTimeType::class, array(
            'widget' => 'single_text'
        ))
        ->add('inscription', TextType::class)
        ->add('prixNl',      IntegerType::class)
        ->add('prixL',       IntegerType::class)
        ->add('resultat',    TextType::class)
        ->add('sousType',     EntityType::class, array(
            'class'        => 'CalendrierBundle:SousType',
            'choice_label' => 'nom',
            'multiple'     => false,
            'query_builder' => function (EntityRepository $er) use ($idType) {
                return $er->createQueryBuilder('u')
                    ->where('u.typeId = :type')
                    ->setParameter('type', $idType);
            }
        ))
        ->add('save',        SubmitType::class)
    ;
}