2017-09-26 53 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