Last Updated: February 25, 2016
·
4.727K
· andreia

Symfony2.1: Adding (and/or Removing) fields using Event Subscribers

src/Bundle/Form/Type/NewsType.php

class NewsType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title')
            ->add('body')
        ;

        $subscriber = new AddExpiresAtFieldSubscriber($builder->getFormFactory());
        $builder->addEventSubscriber($subscriber);

    }

    // ...
}

src/Bundle/Form/EventListener/AddExpiresAtFieldSubscriber.php

class AddExpiresAtFieldSubscriber implements EventSubscriberInterface
{
    private $factory;

    public function __construct(FormFactoryInterface $factory)
    {
        $this->factory = $factory;
    }

    public static function getSubscribedEvents()
    {
        return array(FormEvents::PRE_SET_DATA => 'preSetData');
    }

    public function preSetData(FormEvent $event)
    {
        $data = $event->getData();
        $form = $event->getForm();

        if (null === $data) {
            return;
        }

        // if is not new (updating data) add the field
        if ($data->getId()) {
            $form->add($this->factory->createNamed('expires_at', 'datetime', null, array(
                'input'  => 'datetime',
                'widget' => 'single_text',
                'format' => 'dd/MM/yyyy  HH:mm'
            )));
        }
    }
}

And in case you having trouble adding or removing a field:
https://github.com/symfony/symfony/pull/4552#issuecomment-6809655