Skip to main content

Creating a view using ViewModels in Magento2

Creating a view using ViewModels in Magento2




ViewModels are created in order to improve the concept of using Blocks in Magento2. In this tutorial, we are going to discuss how we can use ViewModels in Magento2. 


Versions in which we can use ViewModels


We can use ViewModels in Magento 2.2 and greater versions, XSI object to declare ViewModels in xml file is not available in Magento 2.0 and 2.1. 


Why use ViewModels instead of Blocks 


The concept of ViewModels is introduced to get rid of complex block classes and create separate classes that are easy to maintain. Here we are saying complex block classes because whenever we create a block class it extends \Magento\Framework\View\Element\Template class but if a block class is doing some major functionality we have to use some other dependencies too and we can add those dependencies by overriding the PHP constructor and add your dependencies into it. And whenever we override the constructor we have to pass parent dependencies into the parent constructor too. By doing this we have a lot of dependencies into our class. 


<?php

namespace Blog\Management\Block;

 

class Test extends \Magento\Framework\View\Element\Template

{

   public function __construct(

       \Magento\Backend\Block\Template\Context $context,

       array $data = []

   ) {

       parent::__construct($context, $data);

   }

}


Here, we have added $context which is a whole bunch of dependencies which your logic does not need also we need to pass it to the parent constructor. 

By doing this our block class gets very complex and we cannot use the only dependencies we need for our logic so that we can use VIewModels. 


Use of ViewModels 


ViewModels is a concept to make us follow the SOLID principle that is one class one responsibility so that your code does not mess up with multiple dependencies. We can create separate ViewModels with the only required dependencies which we need to render data in the template. ViewModels are easy to render data to templates. 


Create View using ViewModel 


Step 1:- Create ViewModel 


ViewModel is created inside the Vendor\Module\ViewModel directory. In my case it is, Blog\Management\ViewModel\Testviewmodel.php


<?php

namespace Blog\Management\ViewModel;

 

use Magento\Framework\View\Element\Block\ArgumentInterface;

 

class Testviewmodel implements ArgumentInterface

{

   public function __construct() {

 

   }

 

   public function getSomething()

   {

       return "Display Text";

   }

}


_constructor in ViewModel only holds those dependencies that are required for our own functionality. For now _constructor is blank here but we can add as we want. Every ViewModel must implement Magento\Framework\View\Element\Block\ArgumentInterface class. 


Step 2 :- Create layout XML 


Create layout file inside Vendor\Module\view\frontend\layout\routeid_contsollername_actioname.php

This layout file is initialized by the controller pagefactory object. 


<?xml version="1.0"?>

<page>

   <body>

   <referenceContainer name="content">

      <block name="example-view-model" class="Magento\Framework\View\Element\Template" template="Blog_Management::display.phtml">

   <arguments>

       <argument name="view_model" xsi:type="object">Blog\Management\ViewModel\Testviewmodel</argument>

   </arguments>

</block>

</referenceContainer>

   </body>

</page>


We can use ViewModels using arguments of blocks in an xml file. 

Here, 

We have created a referenceContainer and block

Template file is added here as a block template attribute , Naming convention is :- VendorName_ModuleName::filename.phtml

argument is used to add ViewModel class. 

name of the argument is used to get the ViewModel in a phtml file. 

Blog\Management\ViewModel\Testviewmodel is ViewModel class file path. 


Step 3 :- Create template 


Create template file inside Vendor\Module\view\frontend\templates\display.phtml


<?php

$viewModel = $block->getData('view_model');

$viewModel->getSomeThing(); ?>


Here, 

We can get ViewModel using the way we get the value of the argument. 

$viewmodel = $block->getData(‘view_model’);

view_model is the name of the argument. 

We can call blocks inside a phtml file using $block. 

Then we can call the function of ViewModel from which we want to render data to the template. 



ViewModel makes our code easy to maintain and understand. We just have to define the ViewModel as an argument of block in xml file and template file as an attribute of block. There these both files connect to each other. We can get the argument value using $block->getdata(); in a phtml file so by this we can get the ViewModel and call the function of ViewModel from which we want to render data in our view template. That’s it. Enjoy. 


Comments

Popular posts from this blog

Magento2 CLI

Magento2 CLI  Back after a long break! Starting again with this blog because I found it the most important to understand if we are doing the magento development as magento commands play the most important role here. It really helps us a lot if we know that lĺwhich command we need to run on this action or after any changes.  Let’s start with the basic commands that we use a lot of times during our development.  cache:clean or cache:flush php bin/magento cache:clean Or  php bin/magento  cache:flush Both of these commands are used to clean the cache of Magento2 so that your new changes can be reflected to your store.  Using cache:clean it deletes all the enabled cache of magento2. Disabled caches are not affected with cache:clean but if you are doing cache:flush then it purges all the cache storage of magento wherever its enabled or disabled or it even deletes all the third party cache along with the magento cache.  If you are doing any changes in admin configuration, layout xml file, u

How EAV Model Works in Magento2?

                         How EAV Model Works in Magento2?  EAV Model stands for Entity-Attribute-Value is a very important concept of magento2 to understand how the attributes of entities are stored and works in magento2.  EAV Model is described as :-  Entity - Entity refers to the data items such as customers,orders,catalog,category etc.  Attribute - Attributes of the entities like price is an attribute of the product(entity) is referred here is an attribute. Value - A value of the attribute as $20 is a value for price attribute is referred here is a value.  Use of EAV Model EAV(Entity-Attribute-Value) is used to create new attributes of entities such as products, categories etc. With the use of eav models we don’t need to change the structure of the core tables of attributes thus it increases the scalability of the system.  Let’s have a look at how eav works in Magento2 -  Eav model used many several tables to store the data of the entity attributes. The top most table for the e

Plugins in Magento2

Plugins in Magento2 Unlike Magento1, Magento2 introduces a whole new concept of Plugins or Interceptor. A plugin or interceptor is used to change the behaviour of the method of any class without affecting the actual class. This is a very powerful way to customize the core classes of Magento2.  Plugins are one of the customization methods in Magento2. In plugins, there is a design pattern called “Interception” which means “Inserting code dynamically without changing original class behaviour” and this is what plugins exactly do in Magento2. Plugins modify the behaviour of a plugin class function by intercepting a function call and adding code before, after and around that function’s call.  Plugins are used with public methods only.  Declaring Plugins To declare plugins in Magento2, we have to create di.xml according to the specific area.  Create di.xml inside Vendor/Module/etc for global.   < config >     < type name = "{ObservedType}" >       < plugin name