Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@craigmarvelley
Created November 10, 2012 13:17
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save craigmarvelley/4051034 to your computer and use it in GitHub Desktop.
Save craigmarvelley/4051034 to your computer and use it in GitHub Desktop.
Symfony2 Form Event Subscriber Example
<?php
namespace Acme\Bundle\AppBundle\Form\EventListener;
use Symfony\Component\Form\Event\DataEvent;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvents;
class IsAdminFieldSubscriber implements EventSubscriberInterface
{
/**
* @var FormFactoryInterface
*/
private $factory;
/**
* @param FormFactoryInterface $factory
*/
public function __construct(FormFactoryInterface $factory)
{
$this->factory = $factory;
}
/**
* @return array
*/
public static function getSubscribedEvents()
{
return array(
FormEvents::PRE_SET_DATA => 'preSetData',
FormEvents::BIND => 'bind'
);
}
/**
* Called before form data is set
*
* @param DataEvent $event
*/
public function preSetData(DataEvent $event)
{
$data = $event->getData();
$form = $event->getForm();
if (null === $data) {
return;
}
$checked = $data->hasRole('ROLE_ADMIN');
$form->add($this->factory->createNamed('is_admin', 'checkbox', $checked, array(
'property_path' => false,
'required' => false
)));
}
/**
* Called when the form is bound to a request
*
* @param DataEvent $event
*/
public function bind(DataEvent $event)
{
$data = $event->getData();
$form = $event->getForm();
if (null === $data) {
return;
}
$value = $form->get('is_admin')->getData();
if ($value) {
$data->addRole('ROLE_ADMIN');
} else {
$data->removeRole('ROLE_ADMIN');
}
}
}
<?php
namespace Acme\Bundle\AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Acme\Bundle\AppBundle\Form\EventListener\IsAdminFieldSubscriber;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('username')
->add('email')
;
$subscriber = new IsAdminFieldSubscriber($builder->getFormFactory());
$builder->addEventSubscriber($subscriber);
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\Bundle\AppBundle\Entity\User'
));
}
public function getName()
{
return 'user';
}
}
@shairyar
Copy link

shairyar commented May 9, 2017

does not seem to be working in Symfony 3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment