Hello Magento Friends,
In this article, we will focus on the most important functionality, How to Use ViewModels in Magento 2. Did you missed the previous article? No worries! It is right here. How to set NOINDEX NOFOLLOW for Specific Page in Magento 2.
With the release of Magento 2.2, there have been many improvements and one of them is the ViewModel concept. The ViewModel is a class that we insert to phtml, so that required and relevant data could be accessed from it. Avoid unwanted overriding of the block class using View Model. With the use of ViewModel, you do not need to extend the block class or add dependencies to the block. ViewModel allows passing data and additional functionality to the template file.
Let’s take a look at How to Use ViewModels in Magento 2.
Steps to Use ViewModels in Magento 2:
Step 1: Move to the below path
app\code\Vendor\Extension\view\frontend\layout\custom_layout.xml
And add the code as follows
<block name="custom.block" template="Vendor_Module::custom.phtml"> <arguments> <argument name="viewModel" xsi:type="object">Vendor\Extension\ViewModel\Custom</argument> </arguments> </block>
Step 2: Now, navigate to the below path
app\code\Vendor\Extension\ViewModel\Custom.php
And add the below-mentioned code
<?php namespace Vendor\Extension\ViewModel; use Magento\Framework\View\Element\Block\ArgumentInterface; class Custom implements ArgumentInterface { public function getSomething() { return "Hello World"; } }
Step 3: Finally, move to the below path
app\code\Vendor\Extension\view\frontend\templates\Custom.phtml
And add the following code
<?php $viewModel = $block->getViewModel(); echo $viewModel->getSomething(); ?>
Conclusion:
This way you can Use ViewModels in Magento 2. If you have any doubts, let me know in the comment part. Share the article with your other developer friends and stay updated with us for more.
Happy Coding!