I have a problem with session variable. Basically it's not working and ruining what is working. Here my code :
app/code/vendor/CustomerZipCode/Block/Ziplist.php
<?php
namespace Vendor\CustomerZipCode\Block;
use Magento\Framework\View\Element\Template;
class Ziplist extends \Magento\Framework\View\Element\Template
{
public function __construct(Template\Context $context,array $data = array())
{
parent::__construct($context, $data);
$this->setData('zip','');
}
public function setZipcode($zipcode)
{
$this->setData('zip',$zipcode);
Mage::getSingleton('core/session')->setZipCode($zipcode);
}
}
Should I code a use something or import something for use
Mage::getSingleton('core/session')->setZipCode($zipcode);
?
If someone had the same issue and solve it or see what is wrong I would be really glad.
PS: In case of minus please let me know so that I can improve the post
1 Answer 1
You're using Magento 1 methods to setting up the session data.
You can follow below code to Get/Set/Unset session in Magento 2
protected $_coreSession;
public function __construct(
\Magento\Framework\Session\SessionManagerInterface $coreSession
){
$this->_coreSession = $coreSession;
}
public function setValue(){
$this->_coreSession->start();
$this->_coreSession->setMessage('The Core session');
}
public function getValue(){
$this->_coreSession->start();
return $this->_coreSession->getMessage();
}
public function unSetValue(){
$this->_coreSession->start();
return $this->_coreSession->unsMessage();
}
Hope it Helps!!!
-
Thank you a lot, for confirmation : is it meaning that for something as simple as setting a session variable in Magento I have to write all a class ?SylwekFr– SylwekFr2019年08月29日 12:35:12 +00:00Commented Aug 29, 2019 at 12:35
-
Yes. You can also use \Magento\Backend\Model\Session, \Magento\Catalog\Model\Session, \Magento\Checkout\Model\Session, \Magento\Customer\Model\Session and \Magento\Newsletter\Model\Session as per your requirement.Sumit– Sumit2019年08月29日 12:40:46 +00:00Commented Aug 29, 2019 at 12:40
-
thank you, can I use one of them to always have the zip code in my header ? I mean my requirement is once the user tip the zipcode in the textbox in the header, then when he change page the textbox should always be completed with the zipcode the user tippedSylwekFr– SylwekFr2019年08月29日 12:47:39 +00:00Commented Aug 29, 2019 at 12:47
-
Yes, you can set customer's ZIP code in the session and display it in the header section.Sumit– Sumit2019年08月29日 12:49:55 +00:00Commented Aug 29, 2019 at 12:49
-
1Yes, you can use this reference for your requirement.Sumit– Sumit2019年08月29日 12:55:45 +00:00Commented Aug 29, 2019 at 12:55
Mage::getSingleton('core/session')->setZipCode($zipcode);andMage::getSingleton('core/session')->setZipCode($zipcode);