3

I need to set an additional cookie whenever an anonymous user received a session cookie. This happens when selecting a facet in Search API for example. The specific use case is that I need an extra cookie set specifically for a third-party integration (GTranslate). hook_user_login doesn't meet the use case because the user isn't actually logged in but they do receive a session cookie upon selecting a facet. Is there some event I can subscribe to when that happens so I can inject my custom cookie?

2
  • 1
    I don't think there is a specific event, but you could subscribe to KernelEvents::RESPONSE and set a cookie in the response headers.
    – 4uk4
    Sep 27, 2021 at 10:02
  • @4k4: if you can flesh that out any, you should consider posting that as an answer. I'm going to give that a try today, but I'd like to be able to properly credit you for it if it works. ;) Sep 27, 2021 at 13:02

1 Answer 1

1

You can try out an event response event subscriber. For E.g: Create a file in CUSTOM_MODULE/src/EventSubscriber/SetSessionCookieSubscriber.php

namespace Drupal\CUSTOM_MODULE\EventSubscriber;

use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;

class SetSessionCookieSubscriber implements EventSubscriberInterface {
  public function onResponse(FilterResponseEvent $event) {
    /** @var Request $request */
    $request = $event->getRequest();
    // Check if this is the right request, for example posting facets
    $session = $request->getSession();
    // Check for session values
    $response = $event->getResponse();
    /** Your custom code goes here */
    $response->headers->setCookie(new Cookie(...));
  }
  
  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = ['onResponse'];
    return $events;
  }
}

Register it in your services file CUSTOM_MODULE.services.yml

services:
  CUSTOM_MODULE.setsessioncookie:
  class: Drupal\CUSTOM_MODULE\EventSubscriber\SetSessionCookieSubscriber
  tags:
    - { name: event_subscriber }
2
  • 1
    I've added my comment to the code.
    – 4uk4
    Sep 28, 2021 at 9:16
  • Thanks 4K4 for the edit. Sep 28, 2021 at 17:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.