Score:1

How do I set/get cookies in a controller (custom module)?

bs flag

I have a module and I need to set a simple cookie (if not exists). And after each request I need to read the value of the cookie and maybe update.

I have read many articles and tried many ways but no success. The only one, which works, returns a "response" object. But my controller should still work, even after response->header sent/saved.

This is the controller code.


namespace Drupal\my_custom_mod1\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;

class myController extends ControllerBase {

    public function main() {
      $cookie = new Cookie(
        "my_cookie_name",                      
        'some value for the cookie',                                       
        (new \DateTime('now'))->modify("+111 day"), 
        "/",                                     
      );
      $res = new Response();
      $res->headers->setCookie($cookie);
      return $res; // if this line deactivated, no cookie will be set

      return [
        '#type' =>      'inline_template',
        '#context' => [
          'my_html_output' => " my text / html output "
        ]
      ];
    }

}
4uk4 avatar
cn flag
If you want to set a cookie on a rendered page you have to use an event subscriber and set it on the rendered HTML response. BTW Drupal doesn't work well with cookies, better use session values.
Jaypan avatar
de flag
Do you need the cookie to be read by external applications? That's pretty much the only use I can think of for working with cookies in Drupal 8+. Maybe there's a Drupal API that would serve you better.
Kevin avatar
in flag
You can't do it this way. The controller has to return a Response in this instance, and not a render array. You can't do both. The headers have to make it back to the client. That said, unless you have a very specific reason for using cookies, its best to avoid them. Managed hosting platforms like Acquia, Pantheon etc typically have a proxy server that strips out cookies going in/out unless you use a specific naming convention. Also note that cookies will interfere and or stop things from being cached, so expect a performance hit.
Eryk avatar
bs flag
Thank you! I think Drupal sessions expire faster than cookies. That's why I need to work with cookies. It is about a "Favorites Module" for an educational institution. Anonymous users should be able to mark courses on the MyFavoritesList (MVL) so they can find them later. They should also be able to add all the other pages like contact, news, etc. And they should still be able to see this list a few months later. Of course, if the browser cache has not been emptied.
id flag
It seems like durable information like that should be stored with the user account, server-side.
Kevin avatar
in flag
Cookies expire. This should be tracked in user accounts.
Jaypan avatar
de flag
You want private temp store.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.