Find the code below,
<?php
namespace Namespace\Modulename\Controller\Index;
use Magento\Framework\Session\SessionManagerInterface;
use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory;
use Magento\Framework\Stdlib\Cookie\PublicCookieMetadata;
use Magento\Framework\Stdlib\CookieManagerInterface;
class Classname extends \Magento\Framework\App\Action\Action
{
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\Registry $registry,CookieManagerInterface $cookieManager,
CookieMetadataFactory $cookieMetadataFactory,
SessionManagerInterface $sessionManager
)
{
$this->registry = $registry;
$this->_cookieManager = $cookieManager;
$this->_cookieMetadataFactory = $cookieMetadataFactory;
$this->_sessionManager = $sessionManager;
return parent::__construct($context);
}
public function execute()
{
$seller_id = $this->getRequest()->getParam('seller_id');
$this->registry->register('seller_id',$seller_id);
//$this->deleteCookie(); this is for delete the cookie
$this->setCookie();
return true
}
public function deleteCookie()
{
$duration = '86400';
$this->_cookieManager->deleteCookie(
'seller_id',
$this->_cookieMetadataFactory
->createCookieMetadata()
->setPath($this->_sessionManager->getCookiePath())
->setDomain($this->_sessionManager->getCookieDomain())
);
return true;
}
public function setCookie()
{
$duration = '86400';
$metadata = $this->_cookieMetadataFactory
->createPublicCookieMetadata()
->setDuration($duration)
->setPath($this->_sessionManager->getCookiePath())
->setDomain($this->_sessionManager->getCookieDomain());
$this->_cookieManager->setPublicCookie(
'seller_id',
$this->getSellerId(),
$metadata
);
return true;
}
public function getSellerName()
{
return $this->registry->registry('seller_id');
}
}