viewmodels-magento-2 viewmodels-magento-2

How to Use ViewModels in Magento 2 (Working Examples)

Magento 2 has introduced ViewModels from Magento 2.2 onwards. However Many developers are not aware of it. Developers are still using helpers in the template file when they want to render any custom logic inside the specific block. Today we will see how to use ViewModels in Magento 2 with working examples.

If you are using helper in your template file, you must face this warning “The use of helpers in templates is discouraged. Use ViewModel instead” while validating your code against Magento 2 coding standard. This warning indicating that you should always use ViewModel instead of helpers.

Use Case

For example, you are using the product attachment module in your project. Now you would like to display the product attachment link on your product list page, under each product. You know the product attachment module has implemented one helper file to get the product attachment link. So instead of directly using the helper file inside your list. phtml file uses the following way to inject the product attachment link.

Step 1: Extend catalog_category_view.xml file under your custom theme and inject a ViewModel using below code.

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="category.products.list">
            <arguments>
                <argument name="view_model" xsi:type="object">CodextblogDemoViewModelProduct</argument>
            </arguments>
        </referenceBlock>
    </body>
</page>

Step 2: Create Product.php file under your custom module ViewModel directory. Add below code in that file.

<?php

namespace CodextblogDemoViewModel;

use MagentoFrameworkViewElementBlockArgumentInterface;

class Product implements ArgumentInterface
{

    public function getAttachmentLink($_product)
    {
        //logic to get attachment link base on product object
        return $link;
    }

}

Step 3: Now extend list.phtml under your custom theme and utilize the ViewModel’s function and render the link.

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/** @var $block MagentoCatalogBlockProductView */
/** @var $viewModel CodextblogDemoViewModelProduct */
?>

<?php
$_product = $block->getProduct();
$viewModel = $block->getData('view_model');
?>
<div class="attachment">
 <a href="<?php echo $viewModel->getAttachmentLink($_product); ?>">
  <?php echo __('Download Attachment')?>
 </a>
</div>

To Display same link in product page, we will use same ViewModel class. We will inject ViewModel in appropriate block and utilize it.
Step 1: Extend catalog_product_view.xml file under your custom theme and inject a ViewModel using below code.

<?xml version="1.0"?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
	<body>
		<referenceBlock name="product.info.addtocart">
				  <arguments>
				      <argument name="view_model" xsi:type="object">CodextblogDemoViewModelProduct</argument>
				  </arguments>
		</referenceBlock>
	</body>
</page>

Step 2: Utilize same ViewModel File created in above example.

Step 3: Now extend addtocart.phtml under your custom theme and utilize the ViewModel’s function and render the link.

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/** @var $block MagentoCatalogBlockProductView */
/** @var $viewModel CodextblogDemoViewModelProduct */
?>

<?php
$_product = $block->getProduct();
$viewModel = $block->getData('view_model');
?>
<div class="attachment">
 <a href="<?php echo $viewModel->getAttachmentLink($_product); ?>">
  <?php echo __('Download Attachment')?>
 </a>
</div>

Conclusion

Whenever you want to add functionality to your template file, use ViewModels instead of helpers. You can read more about ViewModels on official Magento 2 Devdocs.

Still, Have questions? Feel free to write in comment.

Written by

Chirag

Chirag is a Founder & eCommerce Technology Leader at MageArmy. He leads the eCommerce development team and drives the company’s technology vision, helping businesses build, scale, and optimize high-performing online stores. With years of experience in eCommerce development, he has worked with businesses across industries to solve complex technical challenges and create scalable digital commerce solutions. He loves sharing practical insights about eCommerce development, Magento, Adobe Commerce, and the latest trends in digital commerce to help online businesses grow and succeed.