Magento 2 Session – How to Set Session Variable

magento2sessionvariables

I need to set a variable session in Magento, do I do just procedural PHP or is there a proper way in Magento 2 ?

Example :

$_SESSION['myKey'] = "00001";

@AnsarHunsain code help me, but I can't get my value into another page. My page and my block are on the same module than the block where I've defined getCheckoutSession.

I have this error with this :

  echo $block->getCheckoutSession()->getCommande();

Call to a member function getCommande() on null

Best Answer

You can use to set and get custom session value like below

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        

    $catalogSession = $objectManager->get('\Magento\Catalog\Model\Session');
    //customerSession  \Magento\Customer\Model\Session;
    //checkoutSession = \Magento\Checkout\Model\Session;

    // set session variables and their value
    $catalogSession->setMyName('Test');


    // print session variables value
    echo $catalogSession->getMyName(); // Test


    // Unset session
    $catalogSession->unsMyName();

You can use dependency injection also like below

<?php
namespace Vendor\Module\Block;
class Session extends \Magento\Framework\View\Element\Template
{    
    protected $_catalogSession;


    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Catalog\Model\Session $catalogSession,
        array $data = []
    )
    {        
        $this->_catalogSession = $catalogSession;
        parent::__construct($context, $data);
    }

    public function _prepareLayout()
    {
        return parent::_prepareLayout();
    }

    public function getCatalogSession() 
    {
        return $this->_catalogSession;
    }  
}
?>

Use below code in phtml file

$block->getCatalogSession()->setMyName('Test');
echo $block->getCatalogSession()->getMyName(); // Test