Gaylord.P
Gaylord.P

Reputation: 1468

Symfony : redirect after submit in Twig render() method

I have a few posts in Twig view. For each post, I want to add a form comment.

For best reusable, I call render(controller()) in Twig.

Twig :

{{ render(controller('App\\Controller\\User\\PostController::comment',
    {
        'post': post,
    }
)) }}

Controller :

public function comment(Request $request, Post $post): Response
{
    $comment = new PostComment();
    $comment->setPost($post);

    $form = $this->get('form.factory')->createNamedBuilder('post_comment_' . $post->getId(), PostCommentType::class, $comment)->getForm();
    $form->handleRequest($this->get('request_stack')->getMasterRequest());

    if ($form->isSubmitted() && $form->isValid()) {
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($comment);
        $entityManager->flush();

        $this->redirectToRoute(...); // ERROR
    }

    return $this->render('user/post/_comment.html.twig', [
        'form' => $form->createView(),
    ]);
}

But I can't redirect after submit. I understand that it's complicated from a view, HttpRequest has already passed.

This is error :

An exception has been thrown during the rendering of a template ("Error when rendering "http://project.local/index.php/u/root/post" (Status code is 302).").

Do you have a solution for me ? Thanks you :)

Upvotes: 1

Views: 8175

Answers (1)

goto
goto

Reputation: 8162

The main problem is handling your invalid form.

1) redirection during submission

If you don't care your user is on the comment page (not the render) if his form is invalid, you can simply add in your rendered template:

{# 'user/post/_comment.html.twig' #}
{{ form_start(form, {'action': path('your_comment_route')}) }}

or

2) Redirecting using javascript after submission

If you want the user to stay in the same page if the form has error, I don't see any other solution than adding a parameter to change the result of your controller

{{ render(controller('App\\Controller\\User\\PostController::comment', {
        'post': post,
        'embedded': true,
 } )) }}

Then in your controller

if ($form->isSubmitted() && $form->isValid()) {
        if($embedded) {
           return $this->render('user/post/success.html.twig', [
              //call this route by javascript?
              'redirectRoute': $this->generateUrl()//call it in twig, it's just for better understanding
           ])
        } else {
            $this->redirectToRoute(...); 
        }
    }

Upvotes: 1

Related Questions