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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加