Skip to content

Instantly share code, notes, and snippets.

@mborodov
Last active January 18, 2020 10:33
Show Gist options
  • Save mborodov/251b2922603468d0583358a144e3d98a to your computer and use it in GitHub Desktop.
Save mborodov/251b2922603468d0583358a144e3d98a to your computer and use it in GitHub Desktop.
Magento 2 Cookies

Sample work with Cookie in Magento 2

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cookieManager = $objectManager->get('Magento\Framework\Stdlib\CookieManagerInterface');

// set cookie value
$cookieManager->setPublicCookie('key', 'value');

//get cookie value
$cookieManager->getCookie('key');
@rk610
Copy link

rk610 commented Jan 18, 2020

Working On this code but how to update cookie per value

  class Toolbar extends \Magento\Catalog\Block\Product\ProductList\Toolbar
    {

      public function getLimit()
      {

            $limit = $this->_getData('_current_limit');

            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $cookieManager = $objectManager->get('Magento\Framework\Stdlib\CookieManagerInterface');

            // set cookie value
            $cookiekey = 'cookiemanager';
            $cookievalue = $limit;
            $cookieManager->setPublicCookie($cookiekey, $cookievalue );

            //get cookie value
           
            echo $cookieManager->getCookie($cookiekey);
            //$deletecookie = $cookieManager->deleteCookie($cookiekey);

            // if (isset($cookieValue))
            // {
            //     echo 'Set cookie' .$cookieValue. ' !';
            // }
            // else
            // {
            //      echo 'Delete cookie'.$deletecookie. '!';
            // }

            if ($limit) {
                return $limit;
            }

            $limits = $this->getAvailableLimit();
            $defaultLimit = $this->getDefaultPerPageValue();
            if (!$defaultLimit || !isset($limits[$defaultLimit])) {
                $keys = array_keys($limits);
                $defaultLimit = $keys[0];
            }

            $limit = $this->_toolbarModel->getLimit();
            if (!$limit || !isset($limits[$limit])) {
                $limit = $defaultLimit;
            }

            if ($limit != $defaultLimit) {
                $this->_memorizeParam('limit_page', $limit);
            }

            $this->setData('_current_limit', $limit);
            return $limit;
        }

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment