Okay, so I need to access the current user's role in the form in order to query different things according to the role, it works just fine when creating a new user. Send the logged in user to the form as $options... however, I've noticed when editing the form, the $data option inside $options, it's the entity to edit...
How can I send the current user along the entity to edit without overwriting any of them?
I was trying this:
$current_user = $this->get('security.context')->getToken()->getUser();
$form = $this->createForm(new UserType(), $entity, array(
'action' => $this->generateUrl('user_update', array('id' => $entity->getId())),
'method' => 'POST',
'data' => $current_user,
));
but the 'data' option seems to overwrite the $entity I send above.
How can I send both?
I think to achieve a higher level of quality you would need to declare your form type as a service and receive the SecurityContext object as a dependency, like this:
services:
form.type.user:
class: Acme\DemoBundle\Form\Type\UserType
arguments: ["@security.context"]
tags:
- { name: form.type, alias: user_type }
And declare the form type like this:
class UserType extends AbstractType {
private $securityContext;
public function __construct(SecurityContext $securityContext)
{
$this->securityContext = $securityContext;
}
}
That way you can access the user through the SecurityContext object, which will be injected automatically by Symfony.
Create the form like this:
$form = $this->createForm($this->get('form.type.user'), $data);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments