symfony-forms Example of Symfony Form Events FormEvents::PRE_SET_DATA


Example

Requirement is to check if in a form, ‘Online_date’ field is blank or filled. If it is blank, then fill it with current date, on form load.

Controller calls ‘$form->createForm()” with type “folder”. In “FolderType”, event subscriber “FolderSubscriber” is added.

Controller:

            $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: Gets called from FolderType; where it is registered as Event Subscriber

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());
        }
    }
}