LargeTuna
LargeTuna

Reputation: 2824

Symfony choice type array error: Unable to transform value for property path: Expected an array

Why am I getting an error with this form choice set to multiple. This is coming directly off of Symfonys website. All I changed was the variable name.

 $builder->add('genre', 'choice', array(
    'choices' => array(
        'x'   => 'x',
        'y' => 'y',
        'z'   => 'z',
    ),
    'multiple' => true,
));

This is the error:

Unable to transform value for property path "genre": Expected an array.

Here is my entity class for this variable:

 /**
 * @var string
 *
 * @ORM\Column(name="genre", type="text", nullable=true)
 */
private $genre;

Upvotes: 6

Views: 14198

Answers (5)

Moinkhan
Moinkhan

Reputation: 61

Just add data array (empty array if you don't expect any checkbox to be selected by default, or all the values you want to be selected by default )''multiple' => true, data'=>['']

Upvotes: 0

artemiuz
artemiuz

Reputation: 464

public function getGenre(): array { ...

Upvotes: 0

Erick Mendelski
Erick Mendelski

Reputation: 11

I solve the problem with 'data' option

    ->add('flags', ChoiceType::class, [
        'choices' => [Agent::FLAGS],
        'expanded' => true,
        'multiple' => true,
        'required' => false,
        'data' => Agent::FLAGS,
    ])

i am use a bitwise flags, so the database type is a int, and the screen info is a checkbox with a lot of checkboxes.

using the 'data' i can say to symfony what type of data i will use and everthing works.

Upvotes: 0

Lamri Djamal
Lamri Djamal

Reputation: 291

My solution for bypass error, juste use this code.

explode("|",$response['quest1'])

use explode for solve you problème

Im use | separatore you can replace | by ,

example code in under

 $builder->add('genre', 'choice', array(
'choices' => array(
    'x'   => 'x',
    'y' => 'y',
    'z'   => 'z',
),
  'multiple' => true,
   explode("|",$response['genre']),
));

Upvotes: 0

Francesco Borzi
Francesco Borzi

Reputation: 62024

I can confirm that the comment by qooplmao solves the issue:

The problem is that your entity field $genre is not defied as an array but as a string.

But when multiple choices are enabled, the form field will provide an array as a result, and not a string.

So you can:

  • map genre as an array instead of a string
  • or disable multiple choices by setting multiple to false

I this specific problem I guess that you want to map genre as an array.

Upvotes: 1

Related Questions