flow
flow

Reputation: 137

Function inside object in symfony form builder

I don`t know why i am getting error if i try this:

$builder
->add('product', EntityType::class, array(
'data' => $options['product'],
'placeholder' => 'Wyszukiwarka',
'mapped' => false,
'multiple' => false,
'class' => Products::class,
'attr' => [
    'class' => 'chosen-select order_product',
    'data-placeholder'=>'Wybierz produkt',
    'single_price' => function ($product) {
       $cena = $product->getJson()["products"]["price"];
      dump($cena);
      return $cena;
      }
  ],

'choice_label' => function ($product) {
return  ''.$product->getJson()["products"]["name"] .' | Stan Magazynowy: '.$product->getJson()["products"]["stock"].'';
},
'label' => 'Wybierz produkty'

))

so, function inside 'choice_label' works perfect, why i can`t do the same in attr which contains a par extra attributes for this input. I am getting this error:

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

Why function inside attr object not working ?

Upvotes: 0

Views: 735

Answers (1)

Nicolai Fröhlich
Nicolai Fröhlich

Reputation: 52483

You're using the wrong configuration option. The attr option doesn't accept a callback. In your case - to add an attribute depending on the value of each choice - you need to use choice_attr as found in the documentation.

An example implementation could look like this:

$builder->add('attending', ChoiceType::class, array(
    // [..]
    'choice_attr' => function($choiceValue, $key, $product) {
        return [
            'data-single-price' => $product->getPrice()
        ];
    }
));

Upvotes: 5

Related Questions