Skip to content

Instantly share code, notes, and snippets.

@maximecolin
Created September 13, 2014 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maximecolin/2868492e090fdc75fd8b to your computer and use it in GitHub Desktop.
Save maximecolin/2868492e090fdc75fd8b to your computer and use it in GitHub Desktop.
Protéger un champ de formulaire Symfony2 avec un droit
services:
jdecool_forum_bundle.security_type_extension:
class: JDecool\Bundle\ForumBundle\Form\Extension\SecurityTypeExtension
arguments:
- @security.context
tags:
- { name: form.type_extension, alias: form }
<?php
namespace JDecool\Bundle\ForumBundle\Form\Extension;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Security\Core\SecurityContextInterface;
class SecurityTypeExtension extends AbstractTypeExtension
{
/**
* The security context
* @var SecurityContextInterface
*/
private $securityContext;
/**
* Object constructor
*/
public function __construct(SecurityContextInterface $securityContext)
{
$this->securityContext = $securityContext;
}
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$grant = $options['is_granted'];
if (null === $grant || $this->securityContext->isGranted($grant)) {
return;
}
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$form = $event->getForm();
if ($form->isRoot()) {
return;
}
$form->getParent()->remove($form->getName());
});
}
/**
* {@inheritdoc}
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array('is_granted' => null));
}
/**
* {@inheritdoc}
*/
public function getExtendedType()
{
return 'form';
}
}
<?php
namespace JDecool\Bundle\ForumBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ThreadType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('content', 'textarea')
->add('solved', 'checkbox', [
'required' => false,
'is_granted' => 'ROLE_ADMIN',
])
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'JDecool\Bundle\ForumBundle\Entity\Thread'
));
}
/**
* @return string
*/
public function getName()
{
return 'forum_thread';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment