Magento, Magento 2

How to use viewModel in Magento 2

How to use viewModel in Magento 2

In this tutorial, Today I will explain to how to use viewModel in Magento 2. After Magento 2.2, Magento implement viewModel which is one of the best concept. ViewModel is majorly useful when you want to add some codes in template file without use object manager or without override block file. It will allow to pass data and additional functionality to the template file.

For ex. in topmenu.phtml file if you want to get some customer related data then, you need to get it by object manager. But, if you want to get without object manager and use by construct method then, you need to use viewModel method.

So, Let’s create example for that.

You may also like this :

Step of how to use viewModel in Magento 2 :

1) First of all, Let’s assume that you have created simple module. Now, you need to create default.xml file at app/code/RH/Helloworld/view/frontend/layout/ and paste the below code :

<?xml version="1.0"?>
<!--
/**
 * Created By : Rohan Hapani
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">  
      <body>
        <referenceBlock name="catalog.topnav" template="Magento_Theme::html/topmenu.phtml">
            <arguments>
               <argument name="viewModel" xsi:type="object">RH\Helloworld\ViewModel\Customer</argument>
            </arguments>
        </referenceBlock>
    </body>
</page>

Here, you need to use block of topmenu.phtml file as referenceBlock. You can use your block name for viewModel in which phtml file you want to pass custom data. For call viewModel you need to pass argument inside that referenceBlock and pass viewModel file class as object.

2) Now, create Customer.php file at app/code/RH/Helloworld/ViewModel/ and paste the below code :

<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\ViewModel;

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

    /**
     * @var \Magento\Customer\Model\CustomerFactory
     */
    protected $customerFactory;

    /**
     * @param \Magento\Catalog\Model\CustomerFactory     $customerFactory
     */
    public function __construct(
        \Magento\Catalog\Model\CustomerFactory $customerFactory
    ) {
        $this->customerFactory = $customerFactory;
    }

    public function getCustomerById($id) {
        $customerObj = $this->customerFactory->create()->load($id);
        return $customerObj;
    }
}

Here, you can see that we can inject class without extend parent class inside construct. So, it’s plus point to view model for pass data and more faster to receive data. You need to implement \Magento\Framework\View\Element\Block\ArgumentInterface interface class for view model.

3) Now, you can use that function in topmenu.phtml file using this below way :

<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\ViewModel;

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

    /**
     * @var \Magento\Customer\Model\CustomerFactory
     */
    protected $customerFactory;

    /**
     * @param \Magento\Catalog\Model\CustomerFactory     $customerFactory
     */
    public function __construct(
        \Magento\Catalog\Model\CustomerFactory $customerFactory
    ) {
        $this->customerFactory = $customerFactory;
    }

    public function getCustomerById($id) {
        $customerObj = $this->customerFactory->create()->load($id);
        return $customerObj;
    }
}

You can access viewModel via getData() method by name of the argument and then, you can access function of the viewModel file.

That’s it !!!

I hope this blog is easy to understand about how to use viewModel in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Stay Safe and Stay Connected !!

Tagged , ,