In a Symfony 2 application, I am trying to implement a form with a search box and some additional filters (choice widget). The search box looks for a record in the DB and then displays details about that record. The filters are used to display or hide certain types of details.
This works if no or one record is found because I can then stay within the same controller and action. However, if more than one record is found, I render a different template which displays a selection dialog. Each record in the list is a link back to the original page, but with the record id as a parameter.
When I click on that link, I loose the form data. What is the best way to retain form data across a redirect here (or conditionally display a selection dialog without a redirect)?
There are 2 approaches. One is simple and easy to implement, second allows robots to crawl your search results but needs more time spending and requires external storage.
Symfony's Session
object has so-called flashbag where you can store random data. Basicly it's the same session parameter but clearly indicates that it can be removed in any moment.
Updated @Darragh pointed out that flashbag can be retrieved only once. So I recommend you using Session
object instead. It's stored as session
service in container or app.session
in twig. Session is started automatically first time you write something there.
How it can be implemented:
Upon going back to search results you check this session and retrieve your search set from there.
Main idea is each unique set of search parameters represents own search page with results e.g. /search?hash=ASIDJA12SLDS5KSK2
.
What's this and how it works? Pretty simple: you store each unique set of search parameters in db along with unique hash for this set of parameters. Hash function is not required to be reversible but it should be constant: each set of search parameters should have only one constant hash. Otherwise you'll have 2 different pages with same results that crawling bots can identify as duplicate content.
Logic is following:
/search?hash=*hash*
If user navigates back to search results he will land to /search?hash=*hash*
again. If you implement steps 2 and 3 correctly you don't even need to handle this case.
Optionally you can use reversible hash algorithm (e.g. base64). In this case you don't need external storage but be sure that you won't end up with too big url
You can submit the form on clicking on link! You can make it in jquery
$('a.mylink').live('click', function(){
$('#yourform').submit();
return false;
});
and you can past you Id as a hidden input.