E
E
Evgeny Kramor2018-03-05 09:38:06
symfony
Evgeny Kramor, 2018-03-05 09:38:06

How to implement redirect with redirectToRoute() after form submission in Symfony 3?

There is a form:

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

use AppBundle\Entity\Task;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {

        $task = new Task();
        $task->setTask('Write a blog post');
        $task->setDueDate(new \DateTime('tomorrow'));

        $form = $this->createFormBuilder($task)
            ->add('task', TextType::class)
            ->add('dueDate', DateType::class)
            ->add('save', SubmitType::class, array('label' => 'Create Post'))
            ->getForm();

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            return $this->redirectToRoute('default');
        
        }

        return $this->render('default/index.html.twig', array(
            'form' => $form->createView(),
        ));
        
    }
}

After sending, a redirect should occur: I want to create a routing with an annotation, but after submitting the form it crashes: Unable to generate a URL for the named route "result/index.html.twig" as such route does not exist. How to implement this action correctly? * I would like to note right away that they don’t throw sticks at me: I have been studying symfony for two days.
return $this->redirectToRoute('default');

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Rogov, 2018-03-05
@RogovP

return $this->redirect( $this->generateUrl( 'route_name')

And it's better to use "[]" instead of the "array()" construct

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question