I am trying to overwrite a core template and add my custom logic using a viewModel as follow:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
    <referenceBlock name="name.of.the.core.block" template="Vendor_CustomModule::path/to/template.phtml" />
        <arguments>
           <argument name="viewModel" xsi:type="object">Vendor\CustomModule\ViewModel\Class</argument>
        </arguments>
    </referenceBlock>
</body>

But it's not working.

I know it is possible to inject viewModels into blocks but not sure if is possible by referencing an existing block.

up vote 3 down vote accepted

It is possible and it works as expected!

The reason why it was not working was because I was not implementing the right interface in my viewModel class.

All viewModels need to to implement ArgumentInterface.

namespace Vendor\CustomModule\ViewModel;

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

    }
}

I'm not exactly clear what's your question and what you're trying to do by <arguments> element. But I can say you can't use "template" attribute inside the "<referenceBlock>" element as it's invalid.

Maybe you can redefine the core block with the same name.

  • Hi, yes you can. In fact, it is one of the two ways (and I think the only that works) you can use to replace a block template using layout. You can read more about it here: devdocs.magento.com/guides/v2.2/frontend-dev-guide/layouts/… – diazwatson May 29 at 3:40
  • But the question is about viewModel and the possibility to inject them in a core block to modify the blocks template. – diazwatson May 31 at 12:15

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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