Reputation: 449
i'm using symfony2 and i'm experiencing a strange behavior with my cookies. Here's the process : 1- I render a classic form, nothing tricky -> OK 2- I validate the form and i set a cookie to remember the form is ok
public function indexAction(Request $request)
{
[...]
if ($form->isValid()) {
[...]
$cookie = new Cookie('cookietest', 'rdvalue', time()+3600 * 24 * 365, '/', null, false, false);
$response = new Response();
$response->headers->setCookie($cookie);
$response->prepare($request);
$response->send();
$formSuccess = true;
}
return array('form' => $form->createView(), 'formSuccess' => $formSuccess);
}
All seems to work perfectly at this point. In my rendered index template, i have a rendered controller as follow :
index.html.twig :
{% if formSuccess %}
{{ render(controller('MyBundle:Demo:checkCookie')) }}
{% endif %}
and in my checkCookie action :
public function checkCookieAction(Request $request){
[...]
if($request->cookies->has('cookietest')) <-- return false. If i dump it, i don't see the cookietest cookie
[...]
}
I should be able to see the cookie because i set it up in the previous controller, the one which rendered the index.html.twig page.
And even stranger, if i just refresh the page, the if($request->cookies->has('cookietest'))
line return true this time !!
What i've missed ?
Upvotes: 0
Views: 399
Reputation: 5542
As @Jovan Perovic stated, when you are viewing a page for the first time after form submit, you actually haven't cookie, because you just received it with response.
Solution is to redirect after validate the form:
if ($form->isValid()) {
...
$this->redirect($this->generateUrl('actual_route'));
}
It's recommended in documentation too:
Redirecting a user after a successful form submission prevents the user from being able to hit the "Refresh" button of their browser and re-post the data.
Upvotes: 1
Reputation: 20191
If I'm not wrong, this is the way it is supposed to work. Official PHP
's docs state this:
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE array. Cookie values may also exist in $_REQUEST.
So, I believe your cookie will appear on next request. Am I right?
Upvotes: 1