FormEventsPRE SET DATA
要求是檢查表單中的“Online_date”欄位是空白還是填寫。如果它是空白的,則在表格載荷上填寫當前日期。
控制器呼叫’$ form-> createForm()``with type
folder“。在 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());
}
}
}