Question

Magento 2.3.*

I want to override ViewModel for the override block (custom.block.name). But the issue is my .phtml a file called from the block and it is calling on some condition. Not every time call.

My frontend layout.xml file content is,

<?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="core.block.name">
            <block name="custom.block.name" class="Vendor\Module\Block\CoreBlock" before="-">
            </block>
        </referenceBlock>
        <referenceBlock name="custom.block.name">
            <arguments>
                <argument name="viewModel" xsi:type="object">Vendor\Module\ViewModel\CustomModel</argument>
            </arguments>
        </referenceBlock>
    </body>
</page>

My .phtml file render from block file. If I set the template in .xml then it is working properly.

Any help will be appreciated.

Était-ce utile?

La solution

Based on your comment, You need to set custom.block.name as referenceBlock. Try to use this below code :

app/code/Vendor/Module/view/frontend/layout/customer_account.xml

<?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="customer_account_navigation">
            <block name="custom.block.name" class="Vendor\Module\Block\CoreBlock" before="-">
            </block>
        </referenceBlock>
        <referenceBlock name="custom.block.name">
            <arguments>
                <argument name="viewModel" xsi:type="object">Vendor\Module\ViewModel\CustomModel</argument>
            </arguments>
        </referenceBlock>
    </body>
</page>

NOTE: Replace the argument name(viewModel) with your core ViewModel Name.

app/code/Vendor/Module/Block/CoreBlock.php

<?php

namespace Vendor\Module\Block;

class CoreBlock extends \Magento\Framework\View\Element\Template
{

    /**
     * @var string
     */
    protected $_template = 'Vendor_Module::temp.phtml';
}

app/code/Vendor/Module/ViewModel/CustomModel.php

<?php

namespace Vendor\Module\ViewModel;

class CustomModel implements \Magento\Framework\View\Element\Block\ArgumentInterface
{

    public function getYourFunction()
    {
        $text = "test";
        return $text;
    }
}

app/code/Vendor/Module/view/frontend/templates/temp.phtml

echo $block->getData('viewModel')->getYourFunction();

NOTE: Replace viewModel with your argument name of customer_account.xml.

Output :

enter image description here

Licencié sous: CC-BY-SA avec attribution
Non affilié à magento.stackexchange
scroll top