Created
January 23, 2013 01:41
-
-
Save andreia/4600971 to your computer and use it in GitHub Desktop.
Adding (and/or Removing) fields using Event Subscribers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// 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' | |
))); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// 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); | |
} | |
// ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment