Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set data attribute for EntityType (Sonata Admin)

 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $builder
         ->add('category', EntityType::class, [
             'required' => false,
             'class'    => CashTransactionCategory::class,
             'label'    => 'Category *',
             'attr'     => [
                 'class'       => 'js-cash_category',
                 'placeholder' => 'Select a category'
             ]
     ]);
}

This is a Select2 type input and I'm trying to set something like that data-flag="flag" for each attribute. The flag is set in database. It's possible to make a workaround and set for each row a data attribute ?

like image 360
GasKa Avatar asked Dec 06 '25 07:12

GasKa


1 Answers

I figured out a simple solution and that's by mistake:

$builder
    ->add('category', EntityType::class, [
        'required'    => false,
        'class'       => CashTransactionCategory::class,
        'label'       => 'Category *',
        'attr'        => [
            'class'       => 'js-cash_category',
            'placeholder' => 'Select a category',
        ],
        'choice_attr' => function ($object) {
             return ['data-flag' => $object->getFlag()];
        }
   ]);

And that's because I'm using EntityType instead of ChoiceType. (Maybe this will help someone)

My Symfony version: 3.3.9

like image 168
GasKa Avatar answered Dec 07 '25 19:12

GasKa