How to Use ViewModels in Magento 2 (Working Examples)

viewmodels-magento-2

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.

Example 1: Display Attachment link in Product listing Page using ViewModel

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">Codextblog\Demo\ViewModel\Product</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 Codextblog\Demo\ViewModel;

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

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 \Magento\Catalog\Block\Product\View */
/** @var $viewModel \Codextblog\Demo\ViewModel\Product */
?>

<?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>

Example 2: Display Attachment link in Product Page using ViewModel

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">Codextblog\Demo\ViewModel\Product</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 \Magento\Catalog\Block\Product\View */
/** @var $viewModel \Codextblog\Demo\ViewModel\Product */
?>

<?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.

Want to ask a question or leave a comment?

Leave a Comment

(0 Comments)

All the comments are goes into moderation before approval. Irrelevant comment with links directly goes to spam. Your email address will not be published.

Was this post helpful? Please support Us!

Follow us on twitter or Like us on facebook.

 


Want to Increase your Magento 2 Development Knowledge?

If Yes! Then Subscribe to our newsletter below and get weekly development posts to your inbox.
Subscribe Here
SUBSCRIBE NOW
close-link

To Avoid Spam Downloads, We Want Your Email

We will send you download link right
away. Please submit form below.
SEND ME DOWNLOAD LINK
Close