How to Create, Read, Update and Delete Custom Cookie in Magento 2
Do you want to know how to create, read, update and delete the custom cookie in Magento 2? A cookie is very important for a PHP application. As such, Magento developer often needs a cookie to be store in the client browser to track and read particular behaviour of the visitor.
Today we will see how to create, read, update and delete the cookie in Magento 2 using PHP code and using JS code.
Create, Read, Update and Delete Cookie using PHP
In this example, I’m showing how to manage cookie in observer class. You can use this code snippet in any of your custom module class.
<?php namespace Codextblog\Customcookie\Observer\Frontend\Customer; use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory; use Magento\Framework\Stdlib\CookieManagerInterface; use Magento\Store\Api\Data\StoreInterface; class Makemycookie implements \Magento\Framework\Event\ObserverInterface { const COOKIE_NAME = 'CUSTOMER_GROUP_ID'; public function __construct( CookieMetadataFactory $cookieMetadataFactory, CookieManagerInterface $cookieManager, StoreInterface $store ) { $this->cookieMetadataFactory = $cookieMetadataFactory; $this->cookieManager = $cookieManager; $this->store = $store; } public function execute( Observer $observer ) { $store = $this->store; $customer = $observer->getEvent()->getCustomer(); /*CREATE OR UPDATE COOKIE*/ $this->setStoreCookie($store, $customer); /*READ COOKIE*/ $this->getStoreCookie(); /*DELETE COOKIE*/ $this->deleteStoreCookie($store); } public function setStoreCookie($store, $customer) { $cookieMetadata = $this->cookieMetadataFactory->createPublicCookieMetadata() ->setHttpOnly(true) ->setDurationOneYear() ->setPath('/'); $this->cookieManager->setPublicCookie(self::COOKIE_NAME, $customer->getGroupId(), $cookieMetadata); } public function getStoreCookie() { return $this->cookieManager->getCookie(self::COOKIE_NAME); } public function deleteStoreCookie($store) { $cookieMetadata = $this->cookieMetadataFactory->createPublicCookieMetadata() ->setPath($store->getStorePath()); $this->cookieManager->deleteCookie(self::COOKIE_NAME, $cookieMetadata); } }
Create, Read, Update and Delete Cookie using JS
Create one custom js file and call that file in your phtml template. In one of the article we have already seen how to call custom js file in Magento 2.
define([ 'jquery', 'mage/cookies' ], function ($) { /** create cookie */ $.cookie('CUSTOMER_GROUP_ID', "1", { expires: 7, path: '/' }); /** update cookie */ $.cookie("CUSTOMER_GROUP_ID", "2"); /** read cookie */ $.cookie('CUSTOMER_GROUP_ID'); /** delete cookie */ $.cookie("CUSTOMER_GROUP_ID", null); });
Leave a Comment
(0 Comments)
Useful Magento 2 Articles
Author Info
Chirag
Connect With Me