How to override a block without name?
-
10-10-2020 - |
문제
I am trying to override following file
module-bundle/view/adminhtml/layout/sales_order_creditmemo_new.xml
<?xml version="1.0"?>
<!--
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceBlock name="order_items">
<block class="Magento\Bundle\Block\Adminhtml\Sales\Order\Items\Renderer" as="bundle" template="sales/creditmemo/create/items/renderer.phtml"/>
</referenceBlock>
</body>
</page>
I override it by creating same name layout file in my module
Vendor_App/view/adminhtml/layout/sales_order_creditmemo_new.xml
<referenceBlock name="order_items">
<block class="Vendor\App\Block\Adminhtml\Sales\Order\Items\Renderer" as="bundle" template="Vendor_App::sales/creditmemo/create/items/renderer.phtml"/>
</referenceBlock>
But my class and template are not overridden. I have created the class and phtml in my module.
I tried to override it using di.xml by adding following code.
<preference for="Magento\Bundle\Block\Adminhtml\Sales\Order\Items\Renderer" type="Vendor\App\Block\Adminhtml\Sales\Order\Items\Renderer"/>
And this works, but the problem is, on clicking Update Qty's button, it fetches my template instead of its own template as the layout for Update Qty is different.
I tried above thing with Configurable and simple product both works perfectly, only bundle type is creating issue.
해결책
You can use setChild()
to replace a block by its alias. First create the new block with a name, then call setChild()
via <action>
:
<referenceBlock name="order_items">
<block class="Vendor\App\Block\Adminhtml\Sales\Order\Items\Renderer" name="custom_renderer" template="Vendor_App::sales/creditmemo/create/items/renderer.phtml"/>
<action method="setChild">
<argument name="alias" xsi:type="string">bundle</argument>
<argument name="block" xsi:type="string">custom_renderer</argument>
</action>
</referenceBlock>
다른 팁
Please check my answer here: https://magento.stackexchange.com/a/239387/14403
I believe that is the same solution you are looking for.