The use of ifconfig is for condition which is coming from system config values. The value of this will be 0 and 1(boolean). According to that value, the block will be rendered. Here we learn about in Magento 2 add ifconfig in override block XML.
Any block can be configured to show or not based on a Magento/Config/Model/Config/Source/Yesno system configuration field, using the ifconfig
argument. For the value, use the XPath to the needed field.
[dt_code]<block class=”Namespace\Module\Block\Type” name=”block.example” ifconfig=”my/yesno/field”/>[/dt_code]
There are three ways to set the template for a block:
template
attribute<argument>
instruction<action method="setTemplate">
instructionXPath to the system configuration field. E.g. “section/group/field” (company_users/password/enabled).
Ifconfig will show template only when it has the value true, it does not work as else condition. if you use in else condition then i suggest you creating a helper function and add the conditions in the helper method.
so please follow below steps.
Create Data.php at app/code/Custom/Module/Helper/Data.php
<?php namespace Custom\Module\Helper; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Store\Model\ScopeInterface; class Data extends \Magento\Framework\App\Helper\AbstractHelper { /** * Configuration paths enable module */ const XML_PATH_COMPANY_USERS_PASSWORD_ENABLED = 'company_users/password/enabled'; /** * @var ScopeConfigInterface */ protected $_scopeConfig; public function __construct ( ScopeConfigInterface $scopeConfig ) { $this->_scopeConfig = $scopeConfig; } public function getTemplate() { $enabledModule = $this->_scopeConfig->getValue(self::XML_PATH_COMPANY_USERS_PASSWORD_ENABLED,ScopeInterface::SCOPE_STORE); if ($enabledModule) { $template = 'Custom_Module::company/customer/add.phtml'; } else { $template = 'Magento_Company::company/management/dialog/customer/add.phtml'; } return $template; } }
In the above helper class code , is specified according to the following:
[dt_code] $this->_scopeConfig->getValue ( $path,$scopeType = ScopeConfigInterface::SCOPE_TYPE_DEFAULT,$scopeCode = null ) [/dt_code]
<referenceBlock name="red.block.name"> <action method="setTemplate"> <argument name="template" xsi:type="helper" helper="Custom\Module\Helper\Data::getTemplate"></argument> </action> </referenceBlock>
In the above layout code , is specified according to the following:
<action method=”setTemplate”>.Second priority has the attribute specified as
<referenceBlock name=”…” template=”…”/>, and the lowest priority has the template using <argument>.
If you have any queries regarding this post, use the comment section below!
I hope this help you.
Keep sharing !!
Click one of our contacts below to chat on WhatsApp