Reputation: 1010
I have an image upload, just noticed that that two things happen:
1) Form resubmits on refresh. Obviously do not want that. I found just a flat-PHP answer. I was wondering what would be the symfony way of doing it.
2) After I upload the file I have to refresh to see that image, That's how I noticed problem 1.
Controller Code:
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()));
Upvotes: 0
Views: 300
Reputation: 9330
Resubmit on refresh is the default behavior, because the refresh will make the same request which you have made last. To overcome this you might want a mechanism called PRG. Unfortunately for Symfony there is no built in plugin for this. But you can accomplish this by making a redirect to the same route.
For eg.
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"));
}
This might solve your second problem too, but i'm not sure about it since Symfony uses the cache for faster loading.
But this wasn't the problem actually, it was, after you upload the image you didn't load to the view, because the upload processing happened after loading the thread data.
Hope this helps
Upvotes: 1