Before jumping right into dynamic form generation, let's have a quick review of what a bare form class looks like:

  1. // src/Acme/DemoBundle/Form/Type/ProductType.php 
  2. namespace Acme\DemoBundle\Form\Type; 
  4. use Symfony\Component\Form\AbstractType; 
  5. use Symfony\Component\Form\FormBuilderInterface; 
  7. class ProductType extends AbstractType 
  8.     public function buildForm(FormBuilderInterface $builderarray $options
  9.     { 
  10.         $builder->add('name'); 
  11.         $builder->add('price'); 
  12.     } 
  14.     public function getName() 
  15.     { 
  16.         return 'product'
  17.     } 
If this particular section of code isn't already familiar to you, you probably need to take a step back and first review the Forms chapter before proceeding.

Let's assume for a moment that this form utilizes an imaginary "Product" class that has only two relevant properties ("name" and "price"). The form generated from this class will look the exact same regardless of a new Product is being created or if an existing product is being edited (e.g. a product fetched from the database).

Suppose now, that you don't want the user to be able to change the name value once the object has been created. To do this, you can rely on Symfony's Event Dispatcher system to analyze the data on the object and modify the form based on the Product object's data. In this entry, you'll learn how to add this level of flexibility to your forms.

Adding An Event Subscriber To A Form Class

So, instead of directly adding that "name" widget via our ProductType form class, let's delegate the responsibility of creating that particular field to an Event Subscriber:


  1. // src/Acme/DemoBundle/Form/Type/ProductType.php 
  2. namespace Acme\DemoBundle\Form\Type; 
  4. use Symfony\Component\Form\AbstractType 
  5. use Symfony\Component\Form\FormBuilderInterface; 
  6. use Acme\DemoBundle\Form\EventListener\AddNameFieldSubscriber; 
  8. class ProductType extends AbstractType 
  9.     public function buildForm(FormBuilderInterface $builderarray $options
  10.     { 
  11.         $subscriber = new AddNameFieldSubscriber($builder->getFormFactory()); 
  12.         $builder->addEventSubscriber($subscriber); 
  13.         $builder->add('price'); 
  14.     } 
  16.     public function getName() 
  17.     { 
  18.         return 'product'
  19.     } 

The event subscriber is passed the FormFactory object in its constructor so that our new subscriber is capable of creating the form widget once it is notified of the dispatched event during form creation.


Inside the Event Subscriber Class

The goal is to create a "name" field only if the underlying Product object is new (e.g. hasn't been persisted to the database). Based on that, the subscriber might look like the following:

  1. // src/Acme/DemoBundle/Form/EventListener/AddNameFieldSubscriber.php 
  2. namespace Acme\DemoBundle\Form\EventListener; 
  4. use Symfony\Component\Form\Event\DataEvent; 
  5. use Symfony\Component\Form\FormFactoryInterface; 
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface; 
  7. use Symfony\Component\Form\FormEvents; 
  9. class AddNameFieldSubscriber implements EventSubscriberInterface 
  10.     private $factory
  12.     public function __construct(FormFactoryInterface $factory
  13.     { 
  14.         $this->factory = $factory
  15.     } 
  17.     public static function getSubscribedEvents() 
  18.     { 
  19.         // Tells the dispatcher that we want to listen on the form.pre_set_data 
  20.         // event and that the preSetData method should be called. 
  21.         return array(FormEvents::PRE_SET_DATA => 'preSetData'); 
  22.     } 
  24.     public function preSetData(DataEvent $event
  25.     { 
  26.         $data = $event->getData(); 
  27.         $form = $event->getForm(); 
  29.         // During form creation setData() is called with null as an argument 
  30.         // by the FormBuilder constructor. We're only concerned with when 
  31.         // setData is called with an actual Entity object in it (whether new, 
  32.         // or fetched with Doctrine). This if statement let's us skip right 
  33.         // over the null condition. 
  34.         if (null === $data) { 
  35.             return
  36.         } 
  38.         // check if the product object is "new" 
  39.         if (!$data->getId()) { 
  40.             $form->add($this->factory->createNamed('name''text')); 
  41.         } 
  42.     } 
It is easy to misunderstand the purpose of the if (null === $data) segment of this event subscriber. To fully understand its role, you might consider also taking a look at the Form class and paying special attention to where setData() is called at the end of the constructor, as well as the setData() method itself.
在本事件订阅器中的if (null === $data)代码段的目的很容易引起误解。要完全认识它的作用,您也许需要考虑看看Form类,并特别注意where setData() is called at the end of the constructor以及setData()函数本身。

The FormEvents::PRE_SET_DATA line actually resolves to the string form.pre_set_data. The FormEvents class serves an organizational purpose. It is a centralized location in which you can find all of the various form events available.

While this example could have used the form.set_data event or even the form.post_set_data events just as effectively, by using form.pre_set_data we guarantee that the data being retrieved from the Event object has in no way been modified by any other subscribers or listeners. This is because form.pre_set_data passes a DataEvent object instead of the FilterDataEvent object passed by the form.set_data event. DataEvent, unlike its child FilterDataEvent, lacks a setData() method.
虽然在这个例子中使用form.set_data事件甚至是form.post_set_data事件也同样有效,但使用form.pre_set_data,我们可以保证来自Event对象的数据没有被其它任何订阅器或监听器修改。这是因为form.pre_set_data发送一个DataEvent 对象用以取代通过form.set_data事件发送的FilterDataEvent对象。DataEvent不象其子对象FilterDataEvent,它少一个setData()方法。

You may view the full list of form events via the FormEvents class, found in the form bundle.
您可以通过FormEvents类来查看完整的表单事件列表,该类可以在form bundle中找到。