John Davidson

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

0 comments
Message:


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



My Answer:
To achieve this, you can use the `finishView` method instead of `buildView` in your custom form type class. Here's an updated version of your `AdminEntityType` class:

php
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EntityType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;

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,
]);
}

public function finishView(FormView $view, FormInterface $form, array $options)
{
if ($options['multiple']) {
$view->vars['attr']['class'] = 'form-control select select2-hidden-accessible';
} else {
$view->vars['attr']['class'] = 'form-control select-search';
}
}
}


In this updated version, we are using the `finishView` method to modify the `attr` array of the `FormView` object. This will allow you to change the `class` attribute based on the value of the `multiple` option.

Now, when you use your custom form type in your form builder, the `class` attribute will be set based on the value of the `multiple` option:

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


This should work as expected and set the `class` attribute of the form field based on the `multiple` option.

Rate this post

4 of 5 based on 6292 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us