I am trying to set a cookie on every page load. I did some research and found that event subscribers are the way to go. I created a custom module with event. It starts the event on every page load but the problem is with the cookies.
The $event object has property called response but it is always null. Therefore i cannot set any cookies.
class LanguageCookieSubscriber implements EventSubscriberInterface
{
protected $event;
protected $cookieValue;
public function init(GetResponseEvent $event) {
$this->event = $event;
$cookie = new Cookie("client_language_cookie", $this->cookieValue, 0, '/', NULL, FALSE);
$this->event->getResponse()->headers->setCookie($cookie);
}
}
I also tried to set the response object. Then I can set the cookie but the page will come blank.
$response = new Response();
$this->event->setResponse($response);
$cookie = new Cookie("client_language_cookie", $this->cookieValue, 0, '/', NULL, FALSE);
$this->event->getResponse()->headers->setCookie($cookie);
Any ideas how can i solve this? I need to display the page user has requested and only set cookie.
Thanks in advance.