public function assignRole($username, Role $role) { $bos = $this->bos; $user = $this->bos->findOneBy(array("username" => $username)); if (!$user) { throw new \Exception("User not found"); } $ur = $this->em->getRepository("BOSUserBundle:UserRole")->findOneBy(array("role" => $role, "user" => $user)); if ($ur) { throw new \Exception("This role is already assigned to the user."); } $ur = new UserRole(); $ur->setUser($user); $ur->setRole($role); $this->em->persist($ur); $user->addUserRole($ur); $this->em->persist($user); $this->em->flush(); }