【问题标题】:Image does not show after submission and on refresh form resubmits, symfony2提交后图像不显示,刷新表单重新提交,symfony2
【发布时间】:2013-06-29 07:31:53
【问题描述】:

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

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

【问题讨论】:

    标签: php image forms symfony upload


    【解决方案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 使用缓存来加快加载速度。
    但其实这不是问题,是你上传图片后并没有加载到视图中,因为上传处理是在加载线程数据之后发生的。

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多