ViewModels and block customization in Magento 2

  • Post author:
  • Post category:Magento 2

If you need to add additional business logic to blocks for templates in Magento 2 you don’t need to extend blocks or add additional dependencies to the block now. Since Magento 2.2 you have ViewModels functionality for this purpose.

Let’s check how it works. For example, you want to add some additional business logic to the customer login page. In our example, let’s display additional data ‘Enter your email address on the login form.

customer login form

To do that we do not need to extend current block or create a new one. We do not need to modify our current block either. All we need to do is:

  1. Create app/code/Vendor/Module_Name/ViewModel/CustomDataProvider.php

Our new provider implements Magento\Framework\View\Element\Block\ArgumentInterface

2. Modify app/code/Magento/Customer/view/frontend/layout/customer_account_login.xml

Here we add our new CustomDataProvider as a view_model argument to Magento\Customer\Block\Form\Login block.

3. Modify app/code/Magento/Customer/view/frontend/templates/form/login.phtml template

Here $block->getViewModel()->getCustomData() gets our new view model data provider and call its getCustomData method.

As a result we do not need to extend Magento\Customer\Block\Form\Login block with all its dependencies and create a new block. We just pass our new class with additional logic as a view model argument to the block and call its methods in the template.