Reputation: 97
I made a search form in order to let user choose the city and category (for events). When I land on events.html.twig, I get to right informations. :)
Now, what I'm trying to do is when I go back to the search form, I'd like to keep the values I set last time in the form. I want retrieve them when I go back to the search form so that when I want to change only one thing, I can. ^^
I tried some solution (it's in the comments) by opening a session in order to keep the values entered in the form. At the moment, I am lost in my code. I don't know how I can do it.
<?php
namespace App\Controller;
use App\Form\SearchType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class EventsController extends AbstractController
{
#[Route('/search', name: 'search')]
public function search(Request $request)
{
/* $session = $this->requestStack->getCurrentRequest()->getSession(); */
/* $session->set($data); */
$form = $this->createForm(SearchType::class/* , $data */);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
/* $session->set($data); */
return $this->render('front/events.html.twig', $data);
}
return $this->render('front/search.html.twig', [
'form' => $form->createView(/* $data */)
]);
}
}
Upvotes: 0
Views: 104
Reputation: 1060
You are making several errors. First of all, when you need to read or write something in Session you need to specify a key:
$session->set('search-data', $data);
$data = $session->get('search-data');
See https://symfony.com/doc/current/session.html for more information about the Session component.
Regarding your task, you need the following steps:
$data = $session->get('search-data')
)$this->createForm(SearchType::class, $data )
)$session->set('search-data', $data);
)When you render the form, you do not need to pass again $data (which is already inside the form). Use this:
return $this->renderForm('view_name.twig', [
'form' => $form,
]);
and see https://symfony.com/doc/current/forms.html for more information about the Symfony Form.
Upvotes: 1