0

Following up with my previous question, I need to set and retrieve a cookie in two difference places:

  • set - inside postSave() in a Webform handler
  • get - inside an event subscriber.

In looking around, it seems that there are a few different options for tools, such as \Symfony\Component\HttpFoundation\Response and \Symfony\Component\HttpFoundation\Cookie, or GuzzleHttp\Cookie\SetCookie and GuzzleHttp\Cookie\CookieJar.

For setting the cookie, if I try this in my webform handler:

$values = $webform_submission->getData();

$response = new Response();
$cookie = new Cookie('Dixon customer info form', $values['destination_url'], 0, '/' , NULL, FALSE);
$response->headers->setCookie($cookie);
$response->send();

I get redirected to a blank page. If I try this:

$values = $webform_submission->getData();

$cookie_jar = new CookieJar();
  // Get the current host.
  $host = \Drupal::request()->getSchemeAndHttpHost();

  // Set a cookie for the specific form.
  $cookie = new SetCookie([
    'Name' => 'formEnterCookie',
    'Value' => $values['destination_url'],
    'Domain' => $host,
    'Secure' => FALSE,
  ]);
  $cookie_jar->setCookie($cookie);

no cookie gets set. Using either option, how do I set my cookie within my webform handler?

3
  • Like I've said in the previous question, you can't just send a response. Instead of returning it, which is obviously not possible here, you could set a redirect response in a webform submission method and attach the cookie to it. See drupal.stackexchange.com/a/278212/47547
    – 4uk4
    Commented Sep 30, 2020 at 20:42
  • Well, I'm already in a webform handler as it is. This is obviously pretty simple for you, but not for me; any chance you could throw in an answer with a code sample? Thanks.
    – wonder95
    Commented Sep 30, 2020 at 21:57
  • No, this is not simple. Cookies are not used very often in Drupal and it requires some effort to set and get cookies. You'll get the idea when you read the mentioned topic and the topics linked from there.
    – 4uk4
    Commented Oct 1, 2020 at 6:35

1 Answer 1

0

Just in case someone still needs this: There's a module https://github.com/vaza18/webform_cookie, which work fine for me. It's setting a cookie the old way - using PHP https://www.php.net/manual/en/function.setcookie.php function.

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.