douzhang5199
2017-09-26 06:44
浏览 56
已采纳

Symfony2 - 在预提交/提交表单事件中获取实体

As the title says, I need to get the entity which is going to be deleted in a form event. I'm using Symfony 2.7. I'm able to get entity on POST_SUBMIT event if it gets created/edited, but I'm not able to get it on PRE_SUBMIT, SUBMIT and also POST_SUBMIT before it gets deleted.

What I tried so far (I wrote results of variables in comments)

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 []
}

This is basically how deletion starts. I'll not put the whole functions used by it because I don't think is needed:

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

Any idea?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dqf98772 2017-09-26 07:14
    已采纳

    You don't pass your entity to the form, you can do this by specifying first argument for createFormBuilder call:

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

    and then you should be able to retrieve entity in pre submit event listener.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题