1

I have followed Magento_Catalog Module and I have found

ViewModel folder there.

Can anyone please explain when we need to create ViewModel classes when we creating our custom module?

1 Answer 1

7

ViewModel is a replacement of Block in Magento 2.

When we create any Block file and we need certain data in the template, we define a function in that Block file.

In most cases, we need some custom classes to be injected in the Block constructor to get the data and pass it to the template.

Now to do that, we have to forcefully add 2 additional parameters $context and $data, which we do not need it in our template.

So the ViewModel is a concept to make us follow the SOLID principle (One class, One responsibility).

Overall, you can use ViewModel to avoid defining additional constructor argument $context and $data, and code only what you actually need.

According to the documentation, Block will only be needed if you want to set template file name dynamically or change something in Block functions like _prepareLayout, apart from that, if your template file is fixed, and you want to get data from some collection or model, you can use ViewModel.

You can define ViewModel in layout XML like the following way.

<block name="myblock" template="MyCompany_MyModule::template.phtml">
    <arguments>
        <argument name="view_model" xsi:type="object">MyCompany\MyModule\ViewModel\MyClass</argument>
    </arguments>
</block>

Here, it will take Magento's default block as Class which we normally use to extend our block.

You can create ViewModel file something like below.

MyCompany/MyModule/ViewModel/MyClass.php

<?php

namespace MyCompany\MyModule\ViewModel;

class MyClass implements \Magento\Framework\View\Element\Block\ArgumentInterface
{
    public function __construct(
        SomeCollection $collection
    ) {
        $this->collection = $collection;
    }

    public function getItems($subscription)
    {
        $collection = $this->collection->create();
        return $collection;
    }
}

So this way, we code what we actually need.

In your phtml template file, you can call ViewModel function as below.

$collection = $block->getViewModel()->getItems();

I hope it gives you clarity on ViewModel.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.