Is there a correct way to customize a form depending on the role of the user that requests it?
My scenario is pretty simple: I need to hide some fields if the user has not the ROLE_ADMIN
granted. I tried to avoid the field display on Twig, but
{% if is_granted('ROLE_ADMIN') %}
{{form_row(form.field)}}
{% endif %}
not works, because the form builder bypass this check.
Symfony version: 2.8.2
EDIT
Thanks to the @Rooneyl suggestion I've found the solution:
At first, you need to add the 'role' key to the options parameter. So, in the configureOptions() $options['role']
is always ROLE_USER.
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'MyBundle\Entity\Ticket',
'role' => 'ROLE_USER'
));
}
Then in the controller you have to pass the getRoles()
array:
$user_roles = $this->getUser()->getRoles();
$form = $this->createForm('MyBundle\Form\TicketType', $ticket, array('role' => $user_roles));