4
votes

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, array('attr' => array('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 array('attr' => array('class' => 'rtl')) to every field?

Was looking for something like looping the fields and setting the attribute after adding the field to the builder.

More like this (unfortunately there is no setOption method in FormBuilder):

foreach($builder->all() as $key => $value) {
    $value->setOption('attr', array('class' => 'rtl'));
}

Thanks for any pointers.

2

2 Answers

1
votes

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_merge_recursive($options, $commonOptions);

        $builder->remove($key);
        $builder->add($key, $field->getName(), $options);
    }    
}   
0
votes

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')));
    }
}