提交后图像不显示,刷新表单时重新提交,符号2


Image does not show after submission and on refresh form resubmits, symfony2

我上传了一张图片,刚刚注意到发生了两件事:

1) 刷新时重新提交表单。显然我不想那样。我只找到了一个简单的PHP答案。我想知道做这件事的象征性方式是什么。

2) 上传文件后,我必须刷新才能看到图像,这就是我注意到问题1的原因。

控制器代码:

  public function displayThreadAction($thread_Id)
{
    $em = $this->getDoctrine()->getManager();
    $thread = $em->getRepository('GreenMonkeyDevGlassShopBundle:ForumThread')->find($thread_Id);
    $post = new ForumReply();
    $post->setThreadId($thread);
    $form = $this->createForm(new ReplyImageForm(), $post);
    $request = $this->getRequest();

    if ($request->isMethod('POST')){
        $form->bind($request);
        if ($form->isValid()){
            $image = new ForumReplyImage();
            $image->setImageName($form['imageName']->getData());
            $image->setImageFile($form['imageFile']->getData());
            $image->upload();
            $image->setReplyId($post);
            $em->persist($post);
            $em->persist($image);
            $em->flush();
            $post = new ForumReply();
            $post->setThreadId($thread);
            $form = $this->createForm(new ReplyImageForm(), $post);
        }
    }
    return $this->render('GreenMonkeyDevGlassShopBundle:Forum:forum_thread.html.twig', array('thread' => $thread, 'form' => $form->createView()));

刷新时重新提交是默认行为,因为刷新会发出与上次相同的请求。为了克服这个问题,您可能需要一种称为PRG的机制。不幸的是,Symfony没有内置的插件。但是,您可以通过重定向到相同的路由来实现这一点。

例如

    if ($request->isMethod('POST')){    
        $form->bind($request);    
        if ($form->isValid()){
            $image = new ForumReplyImage();
            $image->setImageName($form['imageName']->getData());
            $image->setImageFile($form['imageFile']->getData());
            $image->upload();
            $image->setReplyId($post);
            $em->persist($post);
            $em->persist($image);
            $em->flush();
            $post = new ForumReply();
            $post->setThreadId($thread);
            $form = $this->createForm(new ReplyImageForm(), $post);
        }
        return $this->redirect($this->generateUrl("current_route"));
    }

这可能也能解决您的第二个问题,但我不确定,因为Symfony使用缓存来加快加载速度
但事实上,这并不是问题所在,而是在上传图像后,你没有加载到视图中,因为上传处理发生在加载线程数据之后。

希望这能帮助