Magento 2 – How to Create and Delete Cookies

cookiemagento2

I've followed this question but set method mentioned there is outdated (Reference: Magento\Framework\App\PageCache\FormKey::set()).

So, a cookie is created like this:

public function set($value, PublicCookieMetadata $metadata)
{
    $this->cookieManager->setPublicCookie(
        self::COOKIE_NAME,
        $value,
        $metadata
    );
}

Where $metadata should be an instance of PublicCookieMetadata.

In one of the plugin I'm using $this->customerCountry->set('India', 10); I know I'm doing wrong here. Instead of passing 10 as the second parameter I need to pass instance of PublicCookieMetadata. How I can do that? I've tried $this->customerCountry->set('India', PublicCookieMetadata $metadat =null); which seems to be wrong. How I can creat and set duration of the cookie?

Best Answer

you need to declare in your class constructor an instance of \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory like this:

protected $cookieMetadataFactory;
public function __construct(
    ....
    \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory,
    ....
) {
    ....
    $this->cookieMetadataFactory = $cookieMetadataFactory;
    ....
}

Then you can get generate the PublicCookieMetadata like this

$cookieMetadata = $this->cookieMetadataFactory->createPublicCookieMetadata()
            ->setDuration(lifetime goes here)
            ->setPath(cookie path goes here)
            ->setDomain(domain goes here)
            ->setSecure(is secure goes here)
            ->setHttpOnly(http only flag goes here);

then use the variable $cookieMetadata as your parameter.

You can find examples of you to generate the cookie metadata in

  • \Magento\Backend\Model\Auth\Session::prolong()
  • \Magento\Persistent\Model\Session::setCookie()
  • \Magento\Sales\Helper\Guest::setGuestViewCookie()
  • \Magento\Store\Model\StoreCookieManager::setStoreCookie()
Related Topic