Okay, i'm trying to check if an user has a specific role, i did this
however, when i do this:
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('nombre',null,array('label' => 'Usuario'))
->add('email')
->add('password', 'repeated', array(
'type' => 'password',
'invalid_message' => 'Los campos deben coincidir',
'first_name' => 'password',
'second_name' => 'confirmar password',
'options' => array('required' => false)
))
->add('cliente', 'entity', array(
'class' => 'ClientesBundle:Cliente',
'empty_value' => 'Company',
'required' => false,
'empty_data' => null)
**)**
$user = $this->securityContext->getToken()->getUser();
**if ($user->getRol() == 'ROLE_SUPER_ADMIN'){**
->add('rol')
**}**
;
}
tried this as well:
**if ($this->securityContext->getToken()->getUser()->getRol() === 'ROLE_SUPER_ADMIN'){**
->add('rol')
**}**
the bolded lines (the ones with **) have the tiny red line that indicates an error, and it's says unexpected if... How do i fix this?
From controller you have to pass user object to form builder
$form = $this->createForm(
new YourType(),
$data,
array('user' => $this->getUser())
);
Then in form builder you can fetch it from $options
:
public function buildForm(FormBuilder $builder, array $options)
{
$user = $options['user']
}
Don't forget to extend setDefaultOptions()
with user
index:
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
...
'user' => null
));
}
If you declare your form type as a service, you can inject the token storage in your class.
So you declare the service in services.yml
like this:
my_form:
class: AppBundle\Services\MyFormType
public: true
arguments: ['@security.token_storage']
And the form class like this:
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
class MyFormType extends AbstractType
{
protected $tokenStorage;
public function __construct(TokenStorage $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$user = $this->tokenStorage->getToken()->getUser();
// Use the user object to build the form
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With