'Symfony Form / FormBuilder: How to add an option or attribute to multiple form fields
I want to add a stylesheet class attribute to most of the fields, but not all.
public function buildForm(FormBuilder $builder, array $options) { $builder ->add('name_short', null, ['attr' => ['class' => 'rtl']] ) ->add('name_long') ->add('profile_education') ->add('profile_work') ->add('profile_political') ->add('twitter') ->add('facebook') ->add('website') ; }
Is there a simpler way than adding the attribute ['attr' => ['class' => 'rtl']]
to every field? Looking for something like looping the fields and setting the attribute after adding the field to the builder.
Thanks for any pointers.
Solution 1:[1]
Came across this and remembered that I recently found a way that works.
Basically iterating over all fields removing and re-adding them with merged options.
Take this example below.
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('name_short')
->add('name_long')
->add('profile_education')
->add('profile_work')
->add('profile_political')
->add('twitter')
->add('facebook')
->add('website')
;
$commonOptions = array('attr' => array('class' => 'rtl'));
foreach($builder->all() as $key => $field)
{
$options = $field->getOptions();
$options = array_replace_recursive($options, $commonOptions);
$builder->remove($key);
$builder->add($key, get_class($field->getType()->getInnerType()), $options);
}
}
Edit: Updated to work with Symfony 3, 4, 5 & 6. Thanks @Massimiliano Arione
Solution 2:[2]
You can do this while constructing the form. Simply hold the field names in an array. If you need to assign different field types, then use an associative array instead.
public function buildForm(FormBuilder $builder, array $options)
{
$fields = array('name_short', 'profile_education', 'profile_work', 'profile_political', 'twitter', 'facebook', 'website');
foreach ($fields as $field) {
$builder->add($fields, null, array('attr' => array('class' => 'rtl')));
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Emii Khaos |