Search code examples
formsinputattributessymfonysymfony-forms

How to set a class attribute to a Symfony form input with an attribut from entity linked


I have in my form a "beds" attribute, an entity linked to another "bedroom". I would like for each input to add a class with the id of the linked entity "bedroom".

$form->add('beds', EntityType::class, array(
    'class' => 'DamiasResaBundle:Bed',
    'query_builder' => function (EntityRepository $er) {
        return $er->createQueryBuilder('b')
                  ->orderBy('b.id', 'ASC');
    },
    'choice_label' => 'id',
    'label' => 'lits ',
    'multiple' => true,
    'expanded' =>true,
    'attr' => array(
        'class' => function ($bed) {
            return $bed->getBedroom()->getId();
        }
     ),
 ))

I have two problems:

  1. 'attr' => array('class'=>'test) return a class attribut in the div containing the input, not a class attribut in the input.
  2. This previous code does not work and returns:

An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class Closure could not be converted to string") in form_div_layout.html.twig at line 358.

Thank you for your help


Solution

  • I see you are using checkboxes. Your code seems ok, and since you use query_builder, the values should be a Bed Entity. Note that attr is not mentioned in the EntityType documentation, and I think you need to use choice_attr instead.

    Can you try this. I'm not sure if it will work or not:

    $form->add('beds', EntityType::class, array(
        'class' => 'DamiasResaBundle:Bed',
        'query_builder' => function (EntityRepository $er) {
            return $er->createQueryBuilder('b')
                        ->orderBy('b.id', 'ASC');
        },
        'choice_label' => 'id',
        'label' => 'lits ',
        'multiple' => true,
        'expanded' =>true,
        'choice_attr' => function ($val) {
                return ['class' => $val->getId()];
        },
    ))
    

    Let us know the results.