Search code examples
phparrayssymfonyobjecttransform

symfony setRole from choice in Form end up in an error


I'm using an entity to catch some role-data into a choice field. This works fine. After sending the form, I can access the value of the choice which looks like:

object(Pr\UserBundle\Entity\Group)#1582 (3) { 
      ["id":protected]=> int(2) 
      ["name":protected]=>string(13) "Chief Roca" 
      ["roles":protected]=> string(21) "ROLE_CUSTOMER_MANAGER"
} 

Now, if I want to save this by

$userData ->setRoles($form->get('usergroups')->getData());

I end up in the following error

Catchable Fatal Error: Argument 1 passed to FOS\UserBundle\Model\User::setRoles() 
must be of the type array, object given, called in /var/www/symfony/webprojekt/src/Pr/UserBundle/Controller/AdminController.php 
on line 427 and defined in /var/www/symfony/webprojekt/vendor/friendsofsymfony/user-bundle/FOS/UserBundle/Model/User.php line 530 

How can I handle this? Do I need to encode it? I think, roles will be stored as an array if I'm right but I'm not sure how to get through there :(

Can anyone give me a hint please?


Solution

  • If you are using FOSUserBundle's default entity setup, then its roles property should contain a serialized array (that's achieved via the object Doctrine field type, so it's totally transparent to work with).

    This means that the correct call that should be made to FOS\UserBundle\Model\User::setRoles() looks like this:

    $user->setRoles(array('ROLE_CUSTOMER_MANAGER'));
    

    An easy workaround in your case would be to use array_map:

    $userData->setRoles(array_map(function($role) {
        return $role->getRoles();
    }, form->get('usergroups')->getData()));
    

    Although, I'd suggest reworking the form/model to expose a better and more logical API (e.g. why does plural Pr\UserBundle\Entity\Group's roles field contain a single string? etc.)