Home > OS >  Symfony choice type array : Unable to transform value for property path : Expected an array
Symfony choice type array : Unable to transform value for property path : Expected an array

Time:11-03

First of all, I'm a new user of Symfony

And actually I'm customing my form EasyAdmin with some fields and I have an issue with this one :

ChoiceField::new('villa')->setChoices($villasChoices)->allowMultipleChoices()

I get this error because of the allowMultipleChoices() func :

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

My field is actually a collection type, That's why I have this error, there is my entity

    #[ORM\OneToMany(mappedBy: 'Name', targetEntity: Villa::class)]
    private Collection $Villa;

public function __construct()
    {
        $this->Villa = new ArrayCollection();
    }

    /**
     * @return Collection<int, Villa>
     */

    public function getVilla(): Collection
    {
        return $this->Villa;
    }

How can I remplace Collection type by Array ?

CodePudding user response:

Try to use AssociationField instead of ChoiceField. AssociationField list entities automatically, while ChoiceField is made to pass array manually.

->setFormTypeOption('multiple', true)

Will do the trick for multiple choice, if your property allow multiples values (OneToMany, ManyToMany)

CodePudding user response:

You must have a form like this:

$form = $this->createFormBuilder($yourEntity)
        ->add('villa', EntityType::class, [
            'class' => Villa::class
            'multiple' => true
        ])
    ;

Set the 'villa' item with EntityType::class and set in the options 'multiple' => true.

In your Villa entity you must set a __tostring method like this:

 public function __toString(): string
{
    return $this->name; //name is a string value
}
  • Related