I have the following entity in Symfony :
class User implements AdvancedUserInterface, \Serializable {
...
private $roles;
...
public function __construct()
{
...
$this->roles = new ArrayCollection();
// Default role for evey user (new entity);
$this->roles->add("ROLE_USER");
...
}
...
function getRoles() {
return $this->roles->toArray();
}
...
function addRole($role){
$this->roles->add($role);
}
function removeRole($role){
$this->roles->remove($role);
}
...
public function serialize()
{
return serialize(array(
...
$this->roles,
...
));
}
/** @see \Serializable::unserialize() */
public function unserialize($serialized)
{
list (
...
$this->roles,
...
) = unserialize($serialized, ['allowed_classes' => false]);
}
}
When I register one user, the default role (ROLE_USER) is added correctly. But when I try to edit one, the database recors does not change :
public function UserAddRole(Request $request){
$userId = $request->request->get("userId");
$role = "ROLE_" . strtoupper($request->request->get("role"));
if($role == "ROLE_USER"){
throw $this->createNotFoundException(
'Cannot remove ROLE_USER role'
);
}
$user = $this->getDoctrine()
->getRepository(User::class)
->findOneBy(array(
'id' => $userId
));
if (!$user) {
throw $this->createNotFoundException(
'User not found'
);
}
$user->addRole($role);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
return new Response("<pre>".var_dump($user->getRoles())."</pre>");
}
There are no constraints on this field, only hardcoded values for now.
The array returned in the response contains the roles I want, but not the database (checked by reloading the page and directly in MySQL.
Any idea ?
Thanks