FormEventsPRE SET DATA

要求是检查表单中的“Online_date”字段是空白还是填写。如果它是空白的,则在表格载荷上填写当前日期。

控制器调用’$ form-> createForm()``with typefolder“。在 FolderType 中,添加了事件订阅者 FolderSubscriber

控制器

            $form = $this->createForm('folder', $folder, array(
                'action' => $this->generateUrl('folders_edit', array('id' => $folder->getId())),
                'method' => 'post'
            ));

FolderType

class FolderType extends AbstractType
 {
    public function __construct( FolderSubscriber $folderSubscriber) 
    {
        $this->folderSubscriber = $folderSubscriber;
    }
    
    public function buildForm(FormBuilderInterface $builder, array $options = array())
    {
       $builder ->add("onlineDate", "datetime", array( 'widget' => 'single_text'));       
       $builder->addEventSubscriber($this->folderSubscriber);
     }
    public function getName()
    {
        return 'folder';
    }
}

FolderSubscriber :从 FolderType 调用; 它被注册为事件订阅者

class FolderSubscriber implements EventSubscriberInterface
{

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

    public function onPreSetData(FormEvent $event)
    {
        $this->setDefaultOnlineDate($event);
    }

    protected function setDefaultOnlineDate(FormEvent $event)
    {
        $content = $event->getData();
        if (!$content->getOnlineDate() instanceof \DateTime){
            $content->setOnlineDate(new \DateTime());
        }
    }
}