0

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

1 Answer 1

4

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
13
  • isn't Object manager to avoid ? And can I replace "setMyName" by "setAnythingElse" ? Sep 19, 2018 at 9:03
  • yes you can use dependency injection at the place of object manager and yes you can use setAnythingElse Sep 19, 2018 at 9:05
  • Ok thanks, I think it's gonna be ok, I have I any trouble I'll come back Sep 19, 2018 at 9:07
  • Should I do this in controller or in a block php file ? Sep 19, 2018 at 9:13
  • if you want to display this session value in phtml file then do it in block specially other wise you can use it anywhere Sep 19, 2018 at 9:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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