I am making my own login application with Symfony2 and I am new at Symfony. I know that I have the FOSUserBundle at my disposal, but I'm trying to learn security on my own first.
My access control defines 3 role: ROLE_SUPER_ADMIN, ROLE_ADMIN and ROLE_USER. In addition the defined roles have other roles associated with them, such as ROLE_ADMIN_VIEW_USERS
I am NOT using the security.context service on entity.roles to map my roles from the entity because I only want to effect ROLE_ADMIN and ROLE_USER. Upon registration every user is given the role ROLE_USER. When a user with ROLE_SUPER_ADMIN views edit page for a user or admin I am trying to put in a checkbox that says 'Make this User an Admin'. If they already have ROLE_ADMIN in the entity getRoles, the box would be checked.
If the box is checked I do this in the action
if ($editForm->isValid()) {
$role = ( 'ROLE_ADMIN' === $editForm->get('role')->getViewData())
? "ROLE_ADMIN"
: "ROLE_USER";
$entity->setRoles(array($role));
$em->flush();
return $this->redirect($this->generateUrl('admin_new_edit', array('id' => $id)));
}
So my question is: How do I check the box if in the entity getRoles() is ROLE_ADMIN? Remember as stated above roles is mapped in the entity, but role is not. I don't want to use roles from the mapped entity because there are several values from the security service that I don't want to use.
$builder
->add('username', 'text')
->add('password', 'password')
->add('email', 'email')
->add('role', 'choice', array(
'mapped' => false,
'label' => 'Make Admin',
'value' => 'ROLE_ADMIN',
'required' => false,
//show following attribute only if entity getRoles is ROLE_ADMIN
//how do i get the value from the entity?
'attr' => array('checked'=>'checked'),
))
Userentity has theROLE_ADMINset (usingUser.getRoles()), so the checkbox is defaulted to checked or not checked? - Jared FarrishUser.getRoles()will give you something like{"roles":["ROLE_USER","ROLE_SUPER_ADMIN","ROLE_ADMIN "]}in return? So the raw return ofgetRoles()isn't telling you ifROLE_ADMINis set because it's actually giving you a JSON string of all roles? Why don't you add aUser.isAdmin()method that gives you that information by getting the data fromUser.getRoles(), reading it, and checking for theROLE_SUPER_ADMINorROLE_ADMINroles in the list? - Jared FarrishisAdminto Entity, what is the entity you're referring?User? - Jared Farrish