2017-09-26 32 views
0

正如標題所述,我需要獲取將要在表單事件中刪除的實體。我正在使用Symfony 2.7。如果創建/編輯了POST_SUBMIT事件,我可以獲得實體,但在PRE_SUBMIT,SUBMIT以及POST_SUBMIT之前,我無法獲取它。Symfony2 - 獲取預先提交/提交表單事件中的實體

我試了一下,到目前爲止(我寫評論的變量結果)

public static function getSubscribedEvents() 
{ 
    return array(
     FormEvents::POST_SUBMIT => 'onPostSubmit', 
     FormEvents::PRE_SUBMIT => 'onPreSubmit', 
     FormEvents::SUBMIT => 'onSubmit' 
    ); 
} 

public function onPreSubmit(FormEvent $event) 
{ 
    dump($event->getForm()->getData()); // <-- null 
    dump($event->getData()); // <-- array:1 ["submit" => ""] 
} 

public function onSubmit(FormEvent $event) 
{ 
    dump($event->getForm()->getData()); // <-- null 
    dump($event->getData()); // <-- array:0 [] 
} 

public function onPostSubmit(FormEvent $event) 
{ 
    dump($event->getForm()->getData()); // <-- array:0 [] 
    dump($event->getData()); // <-- array:0 [] 
} 

這基本上是缺失的啓動方式。我不會把它使用的全部功能,因爲我不認爲是必要的:

public function deleteConfirmAction(Request $request, $id) 
{ 
    $form = $this->createDeleteForm($id); 
    $form->handleRequest($request); 
    $entity = $coreService->getArea($id); 
    if ($form->isValid()) { 
     $coreService->deleteEntity($entity); // will remove also relationships 
     $coreService->persistChanges(); // basically a Doctrine flush() 
     $this->addFlash('success', GlobalHelper::get()->getCore()->translate('flash.entity.delete.success')); 
     return $this->redirect($this->generateUrl('index'))); 
    } 
} 

private function createDeleteForm($id) 
{ 
    return $this->createFormBuilder() 
     ->setAction($this->generateUrl('area_delete_confirm', array('id' => $id))) 
     ->setMethod('POST') 
     ->add('submit', 'submit', array('label' => 'entity.delete', 'attr' => ['class' => 'btn button-primary-right'])) 
     ->getForm(); 
} 

任何想法?

+0

你可以顯示代碼如何刪除你的實體? – gintko

+0

當然@gintko,我要更新這個問題。 – DrKey

+0

和你的'$ this-> createDeleteForm($ id)'方法? – gintko

回答

1

你沒有你的實體傳遞給表單,您可以通過指定第一個參數爲createFormBuilder調用做到這一點:

$this->createFormBuilder(['entity' => $entity]); 

,然後你應該能夠檢索前提交事件監聽實體。

+0

它的工作原理,非常感謝:) – DrKey