Magento Asked by Riccardo Baral on November 23, 2021
This rather trivial requirement turns out be quite a pain for us in recent days, as we couldn’t find a satisfying existing solution, yet.
We are trying to replace certain blocks with a custom template accompanied with a custom block class. Our extension has a system configuration with a couple of boolean inputs (Yes/No), if certain predefined custom blocks should be used. Each custom block replaces one or more default blocks.
If the Merchant selects “No”, nothing should happen to these default blocks.
Example
The search box in the container header-wrapper
in the Luma theme has a block named top.search
. We wand to replace this block with the my-search.phtml
template and the MySearch block class, which inherits from the default search block class. In this case MagentoFrameworkViewElementTemplate
.
<action>
-Tag with ifconfig
-AttributeMy most favorable way was using layout xml files with basic layout definitions to fix our problem. We altered the layout as follows:
<referenceBlock name="top.search" class="TestMyAppBlockMySearch">
<action ifconfig="myapp/components/searchbox" method="setTemplate">
<argument name="template" xsi:type="string">Test_MyApp::my-search.phtml</argument>
</action>
</referenceBlock>
Disadvantage: Magento2 documentation discourages from using
<action>
-Tag. If the search box feature is not used, it still overwrites the default block class.
Disadvantage: It seems a bit hacky to me to use the event system in Magento2 to replace blocks on a certain condition. I get the feeling that this might also impact the performance, if a lot of blocks need to be replaced.
// pseudocode
$layout = $this->getLayout();
$block = $layout->getBlock('top.search');
if ($block) {
// todo only unset on condition
$layout->unsetElement('top.search');
$newBlock = $layout->createBlock('TestMyAppBlockMySearch', 'top.search', []);
$layout->setBlock('top.search', $newBlock);
}
Disadvantage: Possible (unverified) performance and caching issues in the future. Similar to solution B.
The last solution (C) resembles our current pick. However, we are looking for a satisfying solution that works without using any PHP and is written in the Magento2 layout definition (XML). Any ideas?
You can create a plugin for getTemplate()
method for the desired block.
Answered by Roman Snitko on November 23, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP