Magento 2 - block visibility
How to accomplish this business requirement and have the simple and clean code at the same?
Let say we have a defined block in app\code\Vendor\Module\etc\di.xml
where we also set a custom template for this block.
Everyone will probably think this is an easy requirement. You only have to create - in case that you don't have already, one helper class that will have the public method which will read the system config value set in Magento 2 backend and then pass it to the template and write one small if statement to handle this requirement, right? Yeah, that's what I thought first.
Above solution will work fine, but there's one issue - you will have to mess with PHP in html template when this is not needed because, as I'll show you, there's better and more clean solution.
Time to think and find a proper solution that will be simple and clean at one side and without the need to put business logic in a template on other side. Photo by Per Lööv on Unsplash
The solution for this business requirement is to use Magento 2 ifconfig argument in block definition to set the condition that either show or not the block based on Magento/Config/Model/Config/Source/Yesno
option that we have in system config for a certain field.
So we need to set it like below where the my/yesno/field
is the field XPATH - you can find it in database table core_config_data
or in case of custom module it must be defined in Vendor\Module\etc\adminhtml\system.xml
.
Note: field XPATH is from three parts; first one is section id, second one is group id, and the third one is field id.
<block class="Namespace\Module\Block\Type" name="block.example" ifconfig="my/yesno/field">
...
</block>
I hope you find it useful and that it will help you make your code simple and more clean.