Can I and should I call Block methods from its' View Model?

by TheKitMurkit   Last Updated December 28, 2018 18:09 PM

I have a template and should write some logic. I have made a view model and I'm calling it from a template. Should I call block methods from the view model? And if so, how can I do it?



Answers 1


This might look like the following:

<block class="Vendor\Module\Block\Dummy" name="dummy">
    <arguments>
        <argument name="view_model" xsi:type="object">Vendor\Module\ViewModel\Dummy</argument>
    </arguments>
</block>

The newly created class could be used as follows:

namespace Yireo\Example\ViewModel;

class Dummy implements \Magento\Framework\View\Element\Block\ArgumentInterface
{
    public function __construct()
    {
    }
}

In this case, the constructor is still empty. But because the Object Manager is used to instantiate this class, you can modify the constructor to inject new dependencies as you are used to in other classes. You can apply all of the coolness of Magento DI here.

Finally, you can insert the new ViewModel class in your existing PHTML template as follows:

$viewModel = $block->getViewModel();

Reference

Aditya Shah
Aditya Shah
December 28, 2018 17:31 PM

Related Questions


Updated February 04, 2019 07:09 AM

Updated March 08, 2018 18:09 PM

Updated November 01, 2018 17:09 PM

Updated June 15, 2018 00:09 AM

Updated February 22, 2016 01:04 AM