0

我有一个图片上传,只是注意到发生了两件事:

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

1 回答 1

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 使用缓存来加快加载速度。
但这实际上不是问题,它是在您上传图像后您没有加载到视图中,因为上传处理发生在加载线程数据之后。

希望这可以帮助

于 2013-07-02T07:00:29.947 回答