Magento 2.1 – How to Hide Empty Custom Tab

magento-2.1product-attributetabs

I have added the custom attribute tab on the product page. If the tab is empty is must be hidden.

I have created an attribute customtab.

I have added below code in the catalog_product_view.xml inside body tag:

<referenceBlock name="product.info.details">
            <block class="Magento\Catalog\Block\Product\View" name="customtab.tab" template="Magento_Catalog::customtab.phtml" group="detailed_info" >
                <arguments>
                    <argument translate="true" name="title" xsi:type="string">Custom Tab</argument>
                </arguments>
            </block>
        </referenceBlock>

How can I hide the custom attribute tab?

Best Answer

Try following code:

  1. app/code/[VendorName]/[ModuleName]/registration.php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    '[VendorName]_[ModuleName]',
    __DIR__
);
  1. app/code/[VendorName]/[ModuleName]/etc/module.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="[VendorName]_[ModuleName]" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Catalog"/>
        </sequence>
    </module>
</config>
  1. app/code/[VendorName]/[ModuleName]/view/frontend/layout/catalog_product_view.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="product.info.details">
            <block class="Magento\Catalog\Block\Product\View" name="custom.tab" template="[VendorName]_[ModuleName]::product/view/details/custom_tab.phtml" group="detailed_info">
                <arguments>
                    <argument translate="true" name="title" xsi:type="string">Tab Title</argument>
                </arguments>
            </block>
        </referenceBlock>
    </body>
</page>
  1. app/code/[VendorName]/[ModuleName]/view/frontend/templates/product/view/details/custom_tab.phtml
<?php $attributeCode = '<product_attribute_code>'; ?>
<?php echo $block->getProduct()->getData($attributeCode); ?>

Note:

Add your html code in "if" condition, if html data found in tab content then tab will be display on the product page.

Related Topic