Hi everyone, in this tutorial, we will discuss about how to set, retrieve unset session in Magento 2 which help you to build as well as eliminate the session by the quick way through implementing the code. Because with the custom Magento 2 development, it is very essential to learn about the session
These are some list of session types in Magento 2
vendor/magento/module-checkout/Model/Session.php vendor/magento/module-catalog/Model/Session.php vendor/magento/module-newsletter/Model/Session.php vendor/magento/module-persistent/Model/Session.php vendor/magento/framework/Message/Session.php vendor/magento/module-customer/Model/Session.php vendor/magento/module-backend/Model/Session.php vendor/magento/module-checkout/Model/Session.php
Subsequently, you will compose calling Catalog, Customer, and Checkout sessions during the following code.
{ $this->_catalogSession = $catalogSession; $this->_checkoutSession = $checkoutSession; $this->_customerSession = $customerSession; parent::__construct($context, $data); } public function _prepareLayout() { return parent::_prepareLayout(); } public function getCatalogSession() { return $this->_catalogSession; } public function getCustomerSession() { return $this->_customerSession; } public function getCheckoutSession() { return $this->_checkoutSession; } } ?>
Subsequently, with Catalog, Customer, and Checkout sessions, it is viable to locate them from .phtml file.
$block->getCatalogSession()->setMyName('Webnexs'); echo $block->getCatalogSession()->getMyName() . '<br />'; // output: Webnexs $block->getCheckoutSession()->setTestData('Hello World'); echo $block->getCheckoutSession()->getTestData() . '<br />'; // output: Hello World $block->getCheckoutSession()->setTestHello('Test Hello Value'); echo $block->getCheckoutSession()->getTestHello() . '<br />'; // output: Test Hello Value
Follow the below code, in case you want to unset those sessions:
$block->getCatalogSession()->unsMyName(); $block->getCheckoutSession()->unsTestData(); $block->getCustomerSession()->unsTestHello();
Mainly, Customer session authorize gathering the customer information like customer name and email.
// get customer data if ($block->getCustomerSession()->isLoggedIn()) { $customerId = $block->getCustomerSession()->getCustomerId(); $customerData = $block->getCustomerSession()->getCustomer(); echo $customerId . '<br />'; echo $customerData->getFirstname() . ' ' . $customerData->getLastname() . '<br />'; echo $customerData->getEmail() . '<br />'; print_r($block->getCustomerSession()->getCustomer()->getData()); }
Checkout session will show the quote information
// get checkout session data echo $block->getCheckoutSession()->getQuoteId(); print_r($block->getCheckoutSession()->getQuote()->getData());
The above mentioned steps assist you to set, retrieve unset session in Magento 2.
Leave a Reply