Home > OS >  In Symfony how do I redirect to route with datas from search form ? Error : Variable does not exist
In Symfony how do I redirect to route with datas from search form ? Error : Variable does not exist

Time:10-07

I made a search form in order to get events list. This form is displayed in front/search.html.twig. When I submit the search form, I'd like it leads me to front/events.html.twig.

When I submitted it, it says "category" doesn't exist. I don't have this problem when I replaced

return $this->redirectToRoute('events', $data);

with

return $this->render('front/events.html.twig', $data);

but I wish to use to route "events"...

This is my EventsController.php file :

<?php

namespace App\Controller\Front;

use App\Form\SearchType;
use App\Repository\EventsRepository;
use App\Repository\CategoriesRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class EventsController extends AbstractController
{   
    #[Route('/search', name: 'search')]
    public function search(Request $request, SessionInterface $sessionInterface)
    {   
        $data = $request->request->all();
        $sessionSearchFormData  = $sessionInterface->get('searchFormData');

        $form = $this->createForm(SearchType::class, ['data' => $sessionSearchFormData]);
        $form->handleRequest($request);

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

            $data = $form->getData();
            $sessionInterface->set('searchFormData', $data);
            return $this->redirectToRoute('events', $data);
        }

        return $this->renderForm('front/search.html.twig', [
            'form' => $form
        ]);
    }

    #[Route('/events', name: 'events')]
    public function events(
        EventsRepository $eventsRepository, 
        CategoriesRepository $categoriesRepository
    ){
        $events = $eventsRepository->findAll();
        $categories = $categoriesRepository->findAll();
        return $this->render("front/events.html.twig", ['events' => $events, 'categories' => $categories]);
    }

}

CodePudding user response:

Bonjour Emilie,

Your route events does not have parameters. So you can't redirect it using parameters.

CodePudding user response:

you can try something like this :

public function index($name)
{
   return $this->redirectToRoute('events', ['max' => 10]);
}

You can forward to another Controller :

public function index($name)
{
    $response = $this->forward('App\Controller\OtherController::fancy', [
        'name'  => $name,
        'color' => 'green',
    ]);

    // ... further modify the response or return it directly

    return $response;
}

Regards,

CodePudding user response:

hous has found the solution :

The second parameter must be an array :

return $this->redirectToRoute('events', [$data]);

  • Related