3

I tried to set a session from a model file and access this on a phtml file like this and it's not working:

namespace/vendor/Model/ProcessModel.php:

    protected $backendSession;

    public function __construct(
        .....
        \Magento\Backend\Model\Session $backendSession,
        ....
    ) {

        $this->backendSession = $backendSession;
       ...
    }
    public function execute(Observer $observer)
    {

        $postdata = $this->_request->getPost();

        $t1 = $this->backendSession->setMyNam('test');
        $t2 = $this->backendSession->setMyNum('test2');
        $t3 = $this->backendSession->getMyNam();

        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/test.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);
        $logger->info(print_r($t3, true));
    }

}

When I logged this, I received my value in my test.log which means that the session is set.

Now I want to get this session in a phtml file located at \namespace\vendror\view\adminhtml\templates\items\column\name.phtml.

To do that in my helper file located at \namespace\vendror\Helper\Product\View\Personalized.php I have this:

protected $backendSession;

public function __construct(
    ....
    \Magento\Backend\Model\Session $backendSession,
    ....
) {
    ....
    $this->backendSession = $backendSession;
    ...
}

public function getSession(){

    return $this->backendSession;
}

public function getSession1(){

    return $this->backendSession->getMyNam();
}

and in my phtml file name.phtml I try to get this value like this:

$var=$this->helper('namespace\vendor\Helper\Product\View\Personalized');

$nam = $var->getSession()->getMyNam(); 
$num = $var->getSession1();  

and I receive nothing.

If I set my function getSession() to return a value like: return "text"; I receive this value in my phtml, but this is not working only with the session value.

What am I doing wrong? Why can't I see in my phtml the value set in the session?

0

You should not use sessions in templates. You should create wrappers in the block class that the templates can use in order to set/get values.

Using the example above, create the methods in the block

public function setSessionData($key, $value)
{
    return $this->backendSession->setData($key, $value);
}

public function getSessionData($key, $remove = false)
{
    return $this->backendSession->getData($key, $remove);
}

Then use these functions to set or get the session in phtml file.

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.