0

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

  • You have using magento 1 code Mage::getSingleton('core/session')->setZipCode($zipcode); and Mage::getSingleton('core/session')->setZipCode($zipcode); – Amit Bera Aug 29 '19 at 12:30
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 Aug 29 '19 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 Aug 29 '19 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 tipped – SylwekFr Aug 29 '19 at 12:47
  • Yes, you can set customer's ZIP code in the session and display it in the header section. – Sumit Aug 29 '19 at 12:49
  • 1
    Yes, you can use this reference for your requirement. – Sumit Aug 29 '19 at 12:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.