Gabriel Theron
Gabriel Theron

Reputation: 1376

Symfony2 Choice : Expected argument of type "scalar", "array" given

I'm making a form with a choice list. Here's the content of my FormType (only as a test):

$builder->add('regionUser');
$builder->add('roles' ,'choice' ,array('choices' => array(
        "ROLE_ADMIN" => "ROLE_ADMIN",
            "ROLE_USER" => "ROLE_USER",
        ),
        'required'  => true,
        'multiple' => false,
));

When I execute this, I get the following error:

Expected argument of type "scalar", "array" given

What goes wrong? How to solve it?

Upvotes: 1

Views: 3542

Answers (1)

Dave Mascia
Dave Mascia

Reputation: 1364

There is 3 solutions:

  1. Use a multiple choices field to show the roles field. Multiple choices returns a array.

  2. In your form, don't show the "roles" field. Put a new field "role" only in your buildform, not in your entity. (You can fill autmaticaly it with the role hierarchy if you want). In the onSuccess method, get the "role" to set roles for your user.

$user->addRole( $role );

  1. When you create your user class, don't use the UserInterface from the FOSUserBundle. Copy it and change the prototype of the method.

// FOSUserBundle/UserInterface

function setRoles(array $roles);

// YourUserBundle/UserInterface 
function setRoles($roles); 

And change the method in your User Class

// FOSUserBundle/UserInterface 
public function setRoles(array $roles) 
{ 
        $this->roles = array(); 
        foreach ($roles as $role) { 
            $this->addRole($role); 
        } 
} 

// YourUserBundle/UserInterface 
public function setRoles($roles) 
{ 
        if (is_string()) { 
            $this->addRole($roles); 
        } else { 
            $this->roles = array(); 
            foreach ($roles as $role) { 
                $this->addRole($role); 
            } 
        } 
}

You can find more information here: https://groups.google.com/group/symfony2/browse_thread/thread/3dd0d26bcaae4f82/4e091567abe764f9

http://blog.aelius.fr/blog/2011/11/allow-user-to-choose-role-at-registration-in-symfony2-fosuserbundle-2/

https://github.com/FriendsOfSymfony/FOSUserBundle

Upvotes: 2

Related Questions