Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching a cookie to a view in Symfony2

I've found a few questions and pages dealing with cookies in Symfony2 but there doesn't seem to be any clear consensus on exactly how this is supposed to work. I can, of course, just fall back to using PHP's native setcookie function but I feel that it should be an easy thing to do with Symfony2 as well.

I have an action in my controller from which I simply want to return a view with a cookie attached. Thus far I have seem examples basically like this:

use Symfony\Compentnt\HttpFoundation\Response;

public function indexAction() {
  $response = new Response();
  $response->headers->setCookie(new Cookie('name', 'value', 0, '/');
  $response->send();
}

The problem with this is that it sends the response... and doesn't render the view. If I set the cookie without sending the headers the view is rendered but the header (cookie) is not sent.

Poking around I found the sendHeaders() method in the Response object so I'm now manually calling that in my action before returning and that seems to work:

public function indexAction() {
  ...
  $response->sendHeaders();
  return array('variables' => 'values');
}

But is this really the expected pattern to use? In previous versions of symfony I could set the headers in my controller and expect the view controller to handle sending whatever I had sent. It seems now that I must manually send them from the action to get it to work, meaning I have to call this from any action that I set headers in. Is this the case or is there something that I'm missing that's so obvious that no one has bothered to even mention it in any of the documentation?

like image 991
James Alday Avatar asked Oct 27 '11 17:10

James Alday


1 Answers

I think you're on the right lines with:

$response->headers->setCookie(new Cookie('name', 'value', 0, '/'));

If you're trying to render a template then check out the docs here:

Symfony2 Templating Service

If you look at the line:

return $this->render('AcmeArticleBundle:Article:index.html.twig');

basically the render method is returning a response (which the controller then returns) which has the content of the twig template, all you have to do is intercept this:

$response = $this->render('AcmeArticleBundle:Article:index.html.twig');
$response->headers->setCookie(new Cookie('name', 'value', 0, '/'));
return $response;

I think that's it anyway...

like image 128
Kasheen Avatar answered Oct 14 '22 15:10

Kasheen