Search code examples
phpsymfonyfosuserbundlesymfony-2.6

FOSUserBundle add group not properly insert row to mysql db


i try to enable the group function of fosuserbundle, following the doc which can found at fosuserbundle git

RegistrationController:

//...
// I use the controller action to dump and test
// I created the group
//        $g = new Group('super_admin', array('ROLE_USER', 'ROLE_RESELLER', 'ROLE_ADMIN', 'ROLE_SUPER_ADMIN'));
//        $g1 = new Group('admin', array('ROLE_USER', 'ROLE_RESELLER', 'ROLE_ADMIN'));
//        $g2 = new Group('reseller', array('ROLE_USER', 'ROLE_RESELLER'));
//        $g3 = new Group('user', array('ROLE_USER'));
//        
//        $em = $this->getDoctrine()->getEntityManager();
//        $em->persist($g);
//        $em->flush();
//        $em->persist($g1);
//        $em->flush();
//        $em->persist($g2);
//        $em->flush();
//        $em->persist($g3);
//        $em->flush();
$em = $this->getDoctrine()->getEntityManager();
$this->getUser()->addGroup($em->getRepository('vRonnUserBundle:Group')->findOneByName('super_admin'));
exit(var_dump($this->getUser()->getGroups()));

bundle\Entity\User.php

use FOS\UserBundle\Model\User as BaseUser;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

class User extends BaseUser {

//...

/*
* @ORM\ManyToMany(targetEntity="vRonn\UserBundle\Entity\Group", inversedBy="users")
* @ORM\JoinTable(name="fos_user_user_group",
*      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
*      inverseJoinColumns={@ORM\JoinColumn(name="group_id", referencedColumnName="id")}
* )
*/
protected $groups;

//...
public function __construct() {
    parent::__construct();
    // your own logic

    //$this->groups = new ArrayCollection();
}

bundle\Entity\Group.php

use FOS\UserBundle\Model\Group as BaseGroup;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="fos_group")
 */
class Group extends BaseGroup {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToMany(targetEntity="vRonn\UserBundle\Entity\User", mappedBy="groups")
     */
    protected $users;

    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }
}

and i guess the fos_user_user_group table is needed to store the user group record,but is not exists,i google around and there is no command to create it, but i found the structure so i create it manually at phpmyadmin

CREATE TABLE IF NOT EXISTS `fos_user_user_group` (
    `user_id` int(11) NOT NULL,
    `group_id` int(11) NOT NULL,
    PRIMARY KEY (`user_id`,`group_id`),
    KEY `IDX_B3C77447A76ED395` (`user_id`),
    KEY `IDX_B3C77447FE54D947` (`group_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

and finally i think it is all set, so i try dump at the controller

$em = $this->getDoctrine()->getEntityManager();
$this->getUser()->addGroup($em->getRepository('vRonnUserBundle:Group')->findOneByName('admin'));
exit(var_dump($this->getUser()->getGroups()));

and there my user is in group admin, finally???

but when i try the following

//        $em = $this->getDoctrine()->getEntityManager();
//        $this->getUser()->addGroup($em->getRepository('vRonnUserBundle:Group')->findOneByName('admin'));
exit(var_dump($this->getUser()->getGroups()));

and my group is null, so i go check db using phpmyadmin, look at the fos_user_user_group, there is 0 row, anything i miss? the add group will never insert into database.

i google around and found that can assign group to user when user register successfully using event listener, so i give it a try, but same there is no record inserted

bundle\EventListener\UserCreationListener.php

public function onRegistrationSuccess(FormEvent $event) {
        $this->user = $event->getForm()->getData();
        $group_name = 'user';
        $entity = $this->em->getRepository('vRonnUserBundle:Group')->findOneByName($group_name); // You could do that by Id, too
        $this->user->addGroup($entity);
        $this->em->flush();
    }

Solution

  • Finally, i found the solution, i forget to get the usermanager and updateuser

    $em = $this->getDoctrine()->getEntityManager();
    $this->getUser()->addGroup($em->getRepository('vRonnUserBundle:Group')->find(1));
    $userManager = $this->get('fos_user.user_manager');
    $userManager->updateUser($this->getUser());
    exit(var_dump($this->getUser()->getGroups()->first()));
    

    hope will help someone in someday, more about the usermanager click here