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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器