Pierrick Rambaud
Pierrick Rambaud

Reputation: 2434

Use `$options` in an `EntityType` Query_builder

I use a Form Builder to create my form. I added the option team to the FormBuilderInterface to access this property in my form.

class PersonnalStatType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('tag', EntityType::class, [
                'class' => StatTag::class,
                'choice_label' => 'name',
                'query_builder' => function (StatTagRepository $rep/*, $options*/)
                    {
                        return $rep->queryActivated($options['team']);
                    }
                ]
            )
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => PersonnalStat::class,
            'team' => null
        ]);

        $resolver->setAllowedTypes('team', ['null', Team::class]);
    }

The first row is an EntityType and I need to use the team option to perform a query but I don't know how to proceed.

So far I tried :

'query_builder' => function (StatTagRepository $rep)
    {
        return $rep->queryActivated($options['team']);
    }

but the query doesn't know $options

Notice: Undefined variable: options

And

'query_builder' => function (StatTagRepository $rep, $options)
    {
        return $rep->queryActivated($options['team']);
    }

but it doesn't recognize $options

Too few arguments to function App\Form\PersonnalStatType::App\Form{closure}(), 1 passed in /Users/pierrickrambaud/Sites/team-manager/vendor/symfony/doctrine-bridge/Form/Type/EntityType.php on line 32 and exactly 2 expected

Anyone knows a hack ?

Upvotes: 0

Views: 1461

Answers (1)

dbrumann
dbrumann

Reputation: 17166

This should work:

'query_builder' => function (StatTagRepository $rep) use ($options) {
    return $rep->queryActivated($options['team']);
}

Upvotes: 2

Related Questions