提交后的图像不显示,刷新表单重新提交,symfony2

时间:2013-07-02 03:37:10

标签: php image forms symfony upload

我上传了一张图片,只是发现有两件事情发生了:

1)表格在刷新时重新提交。显然不希望如此。我找到了一个平坦的PHP答案。我想知道symfony的做法是什么。

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

1 个答案:

答案 0 :(得分:1)

刷新时重新提交是默认行为,因为刷新将产生您上次提出的相同请求。要克服这个问题,您可能需要一种名为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使用缓存来加快加载速度。
但实际上这不是问题,因为上载图像后你没有加载到视图中,因为加载线程数据后发生了上传处理。

希望这有帮助