We sacrifice by not doing any other technology, so that you get the best of Magento.

We sacrifice by not doing any other technology, so that you get the best of Magento.

    In today’s article we are going to describe that how to create cookie variable and assign value into it. We made a module for it and named it “Magemonkeys_General”

    The first step is to create a block file for this in Cookie.php location which is  app/code/Magemonkeys/General/Block/

    <?php
    namespace MagemonkeysGeneralBlock;
    use MagentoFrameworkViewElementTemplate; 
    
    class Cookie extends MagentoFrameworkViewElementTemplate 
    {
        private $cookieManager;
     
        private $cookieMetadataFactory;
     
        public function __construct(
            MagentoFrameworkStdlibCookieManagerInterface $cookieManager,
            MagentoFrameworkStdlibCookieCookieMetadataFactory $cookieMetadataFactory
        ) {
            $this->cookieManager = $cookieManager;
            $this->cookieMetadataFactory = $cookieMetadataFactory;
        }
     
        public function setCustomCookie($gender = '')
        {
            $publicCookieMetadata = $this->cookieMetadataFactory->createPublicCookieMetadata();
            $publicCookieMetadata->setDurationOneYear();
            $publicCookieMetadata->setPath('/');
            $publicCookieMetadata->setHttpOnly(false);
     
            return $this->cookieManager->setPublicCookie(
                'gender',
                $gender,
                $publicCookieMetadata
            );
        }
     
        public function getCustomCookie()
        {
            return $this->cookieManager->getCookie(
                'gender'
            );
        }
    }

    Then create cookie.phtml file in below location app/code/Magemonkeys/General/view/

    Set cookie :

    $blockName = $block->getLayout()->createBlock('MagemonkeysGeneralBlockCookie');
    $setcookie = $blockName->setCustomCookie('man');

    Get cookie :

    $blockName = $block->getLayout()->createBlock('MagemonkeysGeneralBlockCookie');
    echo $getcookie = $blockName->getCustomCookie();

    That’s it.

    field_5bfb909c5ccae

      Get a Free Quote