Home > Mobile >  Symfony: How to change Form Type option based on another option when extending built-in type?
Symfony: How to change Form Type option based on another option when extending built-in type?

Time:04-20

I want to make a custom type for EntityType of Admin class to leverage code re-use and I have the following code:

class AdminEntityType extends AbstractType
{

    public function getParent(): string
    {
        return EntityType::class;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'class' => Admin::class,
            'label' => 'Admin :',
            'multiple' => false,
        ]);
    }
}

I want to modify $options['attr']['class'] based on $options['multiple'] value. Something like:

    public function buildView(FormView $view, FormInterface $form, array $options)
    {

        if ($options['multiple']) {
            $options['attr']['class'] = 'form-control select select2-hidden-accessible';
        } else {
            $options['attr']['class'] = 'form-control select-search';
        }

        parent::buildView($view, $form, $options);
    }

But the code is not working. What is the proper approach?

In my forms then I want to use

$builder->add(
    'admin',
    AdminEntityType::class,
    [
        'multiple' => true
    ]
);

and decide about multiple param, which should have effect on the attr.class param.

Using Symfony 5.4

CodePudding user response:

In the end I managed to get the desired functionality like this:

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        parent::buildView($view, $form, $options);

        if ($options['multiple']) {
            $view->vars['attr']['class'] = 'form-control select select2-hidden-accessible';
        } else {
            $view->vars['attr']['class'] = 'form-control select-search';
        }
    }

not sure if its correct approach though

  • Related