Useful of View Model in Magento 2

Posted by

Magento 2, a robust and flexible e-commerce platform, introduces a powerful architectural concept known as View Models. This innovative approach enhances the extensibility and customization capabilities for developers, providing a streamlined way to manage and manipulate data within the Magento framework. Sometimes you may not want to add a block class as an alternate we can use this concept.

Understanding of View Model

In the context of Magento 2, a View Model can be thought of as an intermediary between the Controller and the corresponding View. It acts as a data provider, responsible for preparing and presenting specific data to the View layer. This separation of concerns enhances modularity, code organization, and maintainability within the Magento application.

Example

In the following illustrative example, we embark on the journey of integrating a view model into the Catalog product page within Magento. Our focal point is the utilization of the catalog_product_view.xml file, where we seamlessly inject our bespoke view model class. This pivotal customization can find its home either within your meticulously crafted module or within the confines of your theme directory. Notably, the theme directory boasts the precedence, ensuring that any modifications made within it will be given the utmost priority and precedence in the Magento architecture. This versatile approach allows developers to tailor their implementations according to the specific needs of their modules or themes, providing a flexible and customizable framework for Magento 2.

<?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.additional">
            <block name="learningmagento-view-model" class="Magento\Framework\View\Element\Template" template="Learningmagento_General::testofviewmodel.phtml">
                <arguments>
                    <argument name="view_model" xsi:type="object">Learningmagento\General\ViewModel\Product</argument>
                </arguments>
            </block>
        </referenceBlock>
    </body>
</page>

Next thing is will create a class under the ViewModel directory this is important as is a standard way to create ViewModel classes under this directory. We will create a class name product. It must implement the interface Magento\Framework\View\Element\Block\ArgumentInterface otherwise it will throw an error as Exception #0 (UnexpectedValueException): Instance of Magento\Framework\View\Element\Block\ArgumentInterface is expected.

<?php

/**
 *
 * @category  Custom Development
 * @email     contactus@learningmagento.com
 * @author    Mike Bond
 * @website   learningmagento.com
 * @Date      17-12-2023
 */
namespace Learningmagento\General\ViewModel;

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

class Product implements ArgumentInterface
{
    public function getSmallDetails()
    {
        return "Testing of the class ViewModel on product page";
    }
}

Finally, to conclude this process, the addition of a template file becomes imperative. Adhering to Magento’s established standards, we shall christen this template file as “testofviewmodel.phtml.” Following the conventions, this file will be seamlessly incorporated into the module’s view/frontend/template directory, harmonizing with the Magento framework to facilitate the desired rendering of the Viewmodel within the storefront.

<?php

/**
 *
 * @category  Custom Development
 * @email     contactus@learningmagento.com
 * @author    Mike Bond
 * @website   learningmagento.com
 * @Date      17-12-2023
 */
$viewModel = $block->getViewModel();
echo $viewModel->getSmallDetails();

?>

As you can see it adds the message below product details which is in the product additional information which comes after main product details. These classes can be reused in other places like category page, cms pages etc.

Real-World Applications

View Models in Magento 2 find practical applications in various scenarios:

  • Customizing Product Listings: View Models can be employed to manipulate and customize product data before rendering it in product listings.
  • Dynamic Block Content: Developers can use View Models to dynamically adjust block content based on specific conditions or business rules.
  • User Authentication Status: View Models can facilitate the dynamic display of content based on a user’s authentication status, offering personalized experiences.

Do check out our other development articles related to Magento and Adobe commerce in our category Development.