cancel
Showing results for 
Search instead for 
Did you mean: 

how to store value in session using Magento 2

how to store value in session using Magento 2

I want to access observer.php class value into another observer.php class. How can I access one observer class data into another observer class?

2 REPLIES 2

Re: how to store value in session using Magento 2

Hi @rababfzepcc1fc 

To set and get value from session, you can take reference from below code:

public function __construct(
        \Magento\Framework\Session\SessionManagerInterface $session,
        ...
    ){
        $this->session = $session;
        ...
    }
 
    public function setValue($value){
        $this->session->start();
        $this->session->setMessage($value);
     }
 
    public function getValue(){
        $this->session->start();
        return $this->session->getMessage();
    }
 
    public function unSetValue(){
        $this->session->start();
        return $this->session->unsMessage();
    }


If issue resolve, please click on 'Kudos' & Accept as Solution!

Problem solved? Click Accept as Solution!

Re: how to store value in session using Magento 2

Hi @rababfzepcc1fc 

 

For using a value from one observer to another observer class, you must pass the variable in dispatch function in both the events if values are being passed from the controller

 

$this->_eventManager->dispatch('desired_event_for_dispatch', ['value' => "YOUR VALUE"]);

and inject the needful classes in both observer(s) constructor.

 

For storing values in session :

  • Inject session manager Interface into your observer

    public function __construct(
            \Magento\Framework\Session\SessionManagerInterface $sessionObj,
        ){
            $this->sessionObj = $sessionObj;
        }
  • To set, unset and unset values from session, use below methods

        public function setValue($value){
            $this->sessionObj->start();
            $this->sessionObj->setVariable($value);
         }
     
        public function getValue(){
            $this->sessionObj->start();
            return $this->sessionObj->getVariable();
        }
    
        public function unSetValue(){
            $this->sessionObj->start();
            return $this->sessionObj->unsVariable();
        }

NOTE : Don't pass sensitive values in session

 

Please click on 'Kudos' & Accept as Solution if this helped to resolve your issue!

Problem Solved ? Click on 'Kudos' & Accept as Solution ! Smiley Happy