Skip to content

Instantly share code, notes, and snippets.

@clemherreman
Created December 20, 2012 15:35
Show Gist options
  • Save clemherreman/4345986 to your computer and use it in GitHub Desktop.
Save clemherreman/4345986 to your computer and use it in GitHub Desktop.
How to add a field to a symfony2 form on preSetData
<?php
namespace MyNamespace\ReviewBundle\Form\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface,
Symfony\Component\Form\FormFactoryInterface,
Symfony\Component\Form\FormEvents,
Symfony\Component\Form\Event\DataEvent;
/**
* Add Mark Value Subscriber.
*
*/
class AddMarkValueSubscriber implements EventSubscriberInterface
{
/**
* @var \Symfony\Component\Form\FormFactoryInterface The form factory.
*/
private $factory;
/**
* Constructor.
*
* @param \Symfony\Component\Form\FormFactoryInterface $factory The form factory.
*/
public function __construct(FormFactoryInterface $factory)
{
$this->factory = $factory;
}
/**
* Add the label to the mark.
*
* @param \Symfony\Component\Form\Event\DataEvent $event The form event.
*/
public function preSetData(DataEvent $event)
{
$data = $event->getData();
$form = $event->getForm();
if (null === $data) {
return;
}
$form->add($this->factory->createNamed('value', 'interactivemark', null, array(
'label' => $data->getCriteria()->getName(),
'invalid_message' => 'mark.value.invalid',
)));
}
/**
* {@inheritdoc}
*/
static public function getSubscribedEvents()
{
return array(FormEvents::PRE_SET_DATA => 'preSetData');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment