I have to set category id in cookie when customer go to Category page and update cookie with category id when visit again using seperate module.
I have created Observer and set cookie there but not working. I have checked Observer is calling and also getting correct category ID.
Issue is with Cache. if Cache is enabled all is working fine.
events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="catalog_controller_category_init_after">
<observer name="cookieObserver" instance="Vendor\Module\Observer\Category\Data" />
</event>
</config>
Observer - Data.php
<?php
namespace Vendor\Module\Observer\Category;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory;
use Magento\Framework\Stdlib\CookieManagerInterface;
class Data implements ObserverInterface
{
const COOKIE_NAME = 'categoryId';
const COOKIE_DURATION = 86400; // One day (86400 seconds)
protected $cookieManager;
/**
* @var CookieMetadataFactory
*/
protected $cookieMetadataFactory;
public function __construct(
CookieManagerInterface $cookieManager,
CookieMetadataFactory $cookieMetadataFactory
)
{
$this->cookieManager = $cookieManager;
$this->cookieMetadataFactory = $cookieMetadataFactory;
}
/**
* Below is the method that will fire whenever the event runs!
*
* @param Observer $observer
*/
public function execute(Observer $observer)
{
$data = $observer->getData();
$metadata = $this->cookieMetadataFactory->createPublicCookieMetadata()->setDuration(86400)->setPath('/');
$this->cookieManager->setPublicCookie('categoryId', $data['category']->getId(), $metadata);
return $this; }
}
Please provide some suggestion or help.