Expected argument of type "array", "string" given at property path "roles". in Symfony

I’m just trying to add a field hidden in a form by passing a value by default to the field “Roles” in symfony.
I check multiple tutoriel but I did’nt find exactly what I am looking for.

I put how i save the field “roles” in my database, i put how the field “Roles” is declared in my entity and also i put how i try to send the data by hidden in the form.

This is my UsersEntity where i save the “roles”

 * @ORMColumn(name="roles", type="array", nullable=false)
private $roles = [];

public function getRoles(): ?array
    $roles = $this->roles;
    $roles[] = 'ROLE_USER';
    return array_unique($roles);

public function setRoles(array $roles): self
    $this->roles = $roles;

    return $this;

This is my RegistrationFormType

        ->add( 'firstName')
        ->add( 'phone')
        ->add( 'city')
        ->add('roles', HiddenType::class, array(
            'data' => 'ROLE_PARTICULAR'

This is the error

I can’t pass an array, he tells me every time I pass him a string. I tried several syntaxes, I can’t do it, can someone help me please? I’m new to Symfony 5
Thank you for your help.

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 2

Your email address will not be published. Required fields are marked *



Hello, I had the same problem. The cause of the problem in my case was caused by variadic functions in the entity.
I needed to change:

public function setRoles(string …$roles): void


public function setRoles(array $roles): void



Your case might be different. But maybe it would be helpful if you would introduce Data Transformers in your Form.
Perhaps this link would help you: https://symfony.com/doc/current/form/data_transformers.html#example-1-transforming-strings-form-data-tags-from-user-input-to-an-array

Add in your Form a Data Transformer:

$builder->get(‘roles’)->addModelTransformer(new CallbackTransformer(
function ($rolesAsArray) {
return implode(‘, ‘, $rolesAsArray);
function ($rolesAsString) {
return explode(‘, ‘, $rolesAsString);