Magento 2 – How to Add Extra Variable in Session for Cart

cartcustommagento2quotesession

I already referred

How to Set, Retrieve and Unset Session Variables in Magento 2?

When a user clicks on "Add To Cart" button. I would like to Add One Additional Variable in Cart Quote Session.

How to set it & where can I do this may be Observer not sure?

Best Answer

Use the Below Code in your Custom Module to Set, Unset Session

protected $_checkoutSession;
public function __construct(
    \Magento\Backend\Block\Template\Context $context,        

    \Magento\Checkout\Model\Session $checkoutSession,
    array $data = []
)
{        

    $this->_checkoutSession = $checkoutSession;
    parent::__construct($context, $data);
}


public function getCheckoutSession() 
{
    return $this->_checkoutSession;
} 

Now, we set and get session from template (.phtml) file.

$block->getCheckoutSession()->setTestData('123');
echo $block->getCheckoutSession()->getTestData() . '<br />'; // output: 123

Unset session

$block->getCheckoutSession()->unsTestData();

From checkout session, we can fetch quote information.

// get checkout session data
echo $block->getCheckoutSession()->getQuoteId();
print_r($block->getCheckoutSession()->getQuote()->getData());