1

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?

TheTom
  • 934
  • 2
  • 14
  • 40
  • Seems like you are trying to do the same thing as http://stackoverflow.com/questions/8388080/symfony2-fosuserbundle-role-entities – Chase Aug 13 '14 at 15:33
  • 1
    Try `$userData ->setRoles($form->get('usergroups')->getData()->getRoles());` or `$userData ->addRole($form->get('usergroups')->getData()->getRoles());` – M Khalid Junaid Aug 13 '14 at 19:18

1 Answers1

3

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.)

kix
  • 3,290
  • 27
  • 39
  • Kix, Thanky ou very much for this hint. It works. I will change the model of the entity later on. You're right that it is not well planned. – TheTom Aug 14 '14 at 11:51