In this blog, we are going through how to use the view model in Magento 2.
ViewModel allows passing data and additional functionality to the template file without using a block, or object manager. Use a view model when product data and customer data are required in the front end.
This is the best functionality to pass data and show it in the front end.
⇒ let’s start, first of all, you create this file “default.xml” in this path “app/code/vendorname/ModuleName/view/frontend/layout/”
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version=“1.0”?> <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=“VendorName_ModuleName::test.phtml”> <arguments> <argument name=“viewModel” xsi:type=“object”>VendorName\ModuleName\ViewModel\Test</argument> </arguments> </referenceBlock> </body> </page> |
⇒ Then after you create this file “Test.php” in this path “app/code/VendorName/ModuleName/ViewModel/ “.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php namespace VendorName\ModuleName\ViewModel; class Test 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; } } |
⇒ then after you create a template file “test.phtml” in this path “app\code\Vendor\Extension\view\frontend\templates\“.
1 2 3 4 |
<?php $viewModel = $block->getViewModel(); echo $viewModel->getSomething(); ?> |
⇒ I hope you understand this blog. if you have any questions let me know in the comment section
Thank You !!