Magento 2 – How to Use Session Data in View (phtml)

magento2.2.6phtmlsessionview

i can access session data in my controller using \Magento\Framework\Session\SessionManagerInterface

 public function __construct(
        Context $context,
        PageFactory $resultPageFactory,
        \Magento\Framework\Session\SessionManagerInterface $session
    )
    {
        $this->resultPageFactory = $resultPageFactory;       
        $this->session = $session;
        parent::__construct($context);
    }

// assign session
then assess $this->session->setMessage("message") ;

In controller it is working . i need to retrieve session in view . how to i get that. $this->session->getMessage() is not working in view
I need to check session values in phtml.
How to get session variable in magento.

Best Answer

Use a ViewModel to get session data into a view. https://www.yireo.com/blog/2017-08-12-viewmodels-in-magento-2

In your layout file:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Magento\Framework\View\Element\Template" name="customer_login_history" template="Dford_Geoip::login_history.phtml">
                <arguments>
                    <argument name="view_model" xsi:type="object">Dford\Geoip\ViewModel\LoginHistory</argument>
                </arguments>
            </block>
        </referenceContainer>
    </body>
</page>

In your viewModel file:

 <?php

namespace Dford\Geoip\ViewModel;

use Magento\Framework\App\Http\Context;
use Magento\Framework\Session\SessionManagerInterface;

class LoginHistory implements \Magento\Framework\View\Element\Block\ArgumentInterface
{

protected $_httpContext;
protected $_sessionManager;

public function __construct(Context $httpContext, SessionManagerInterface $session)
{
    $this->_httpContext = $httpContext;
    $this->_sessionManager = $session;
}

public function getSessionData()
{
    return $this->_sessionManager->getData();
}
}

Then in your view

<?php
$viewModel = $block->getViewModel();
<?php echo 'test'; ?>
<?php var_dump($viewModel->getSessionData()); ?>

This is what is returned below:

enter image description here

Related Topic