1

I know how to set and get session value in magento 2. Here is what I do:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$mysession = $objectManager->create('Magento\Customer\Model\Session');
$mysession->setMyTestValue('testsession');
$mysession->getMyTestValue();

It works fine.

But I want multiple session value in an array; In simple PHP I've achieved this in following way:

**//Set session in  an array**
<?php
   foreach ($_productCollection as $_product):
   $_SESSION ['mytestvalues'] = array ();
   array_push($_SESSION['mytestvalues'], $_product->getEntityId());
   endforeach;
?>

/**/Get session array**
<?php print_r($_SESSION['mytestvalues']); ?>

Same thing I want to achieve in Magento 2. How to achieve this in magento 2?

1 Answer 1

4

Try this:

protected $mysession;

public function __construct(
    -----
    \Magento\Framework\Session\SessionManagerInterface $coreSession
    ){
    $this->mysession = $coreSession;
    ----
}
    $this->mysession->setMyTestValue(array());
    $sessionValue = $this->mysession->getMyTestValue();
    $datas = array_push($sessionValue, $_product->getEntityId());
    $this->mysession->setMyTestValue($datas);
2
  • Error: Only variables should be passed by reference. Dec 5, 2017 at 6:55
  • I have updated my answer.
    – Nero Phung
    Dec 5, 2017 at 6:58

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.