How to call Viewmodel in – Magento 2

After the Magento 2.2 version, Magento introduces the ViewModel concept, which is looking quite cool and awesome because sometimes you need some custom value of some logic base condition need to add in the phtml file you need to override or extend that block in an earlier version.

View models can be added by passing the view model class as an argument to a template’s block in the layout configuration file. In the following example snippet, TestViewModel is the view model class of the Mage2_Test module passed as an argument to a block.

<block name="mage2.test.viewmodel" template="Mage2_Test::test.phtml">
    <arguments>
        <argument name="test_view_model" xsi:type="object">Mage2\Test\ViewModel\TestViewModel</argument>
    </arguments>
</block>

We can add in any existing layout block as well

<referenceBlock name="checkout.cart.item.renderers.default">
    <arguments>
        <argument name="test_view_model" xsi:type="object">Mage2\Test\ViewModel\TestViewModel</argument>
    </arguments>
</referenceBlock>

The view model class must always implement the interface \Magento\Framework\View\Element\Block\ArgumentInterface.

namespace Mage2\Test\ViewModel;

class TestViewModel implements \Magento\Framework\View\Element\Block\ArgumentInterface
{
    public function getCustomFunction()
    {
      return 'View Model Testing';
    }
}

You can access in related phtml page by calling it below

<?php

/** @var $viewModel \Mage2\Test\ViewModel\TestViewModel */

$viewModel = $block->getTestViewModel();

?>
<h1><?= $block->escapeHtml($viewModel->getCustomFunction()); ?></h1>

 

Need Further Help? or Questions?

Contact Us

Create your account

chatsimple