5

If any one want to remove container (block) like product.info.main from Product Detail Page based on certain conditions or product has attribute with value assigned. Then what is the best approach for achieving This?

Thanks

Nilesh Tighare
  • 915
  • 1
  • 9
  • 22

2 Answers2

7

We can use Event Observer approach...

In YOUR_VENDOR\YOUR_MODULE\etc\frontend\events.xml file, need to add below code:

<event name="layout_generate_blocks_after">
    <observer name="personalize-theme-pdp-customize" instance="YOUR_VENDOR\YOUR_MODULE\Observer\ApplyThemeCustomizationObserver" />
</event>

And in YOUR_VENDOR\YOUR_MODULE\Observer\ApplyThemeCustomizationObserver.php file, need to add below code:

public function execute(Observer $observer)
{
    $action = $observer->getData('full_action_name');
    if ($action !== 'catalog_product_view') {
        return;
    }

    $product = $this->_registry->registry('product');

    if ($product) {
        $attribute = $product->getCustomAttribute('g3d_app_url_default');
        if ($attribute && $attribute->getValue()) {
            /** @var \Magento\Framework\View\Layout $layout */
            $layout = $observer->getData('layout');
            $layout->unsetElement('product.info.main');
        }
    }
}
Black
  • 18,150
  • 39
  • 158
  • 271
Nilesh Tighare
  • 915
  • 1
  • 9
  • 22
0

Using a site wide event to remove a container/block from a specific page is overkill and not the best approach because your condition will be evaluated with every page load, adding a slight overhead to all the pages.

Removing a container/block from a specific page is best achieved by creating an after plugin for the execute method of the controller of the page where you want to remove the container/block. With this approach your condition is only executed when the intended page is loaded.

public function afterExecute(\Magento\[Module]\Controller\[ControllerName] $subject, $result)
{
    if ([your condition]) {
        $result->getLayout()->unsetElement('name_of_container_or_block');
    }

    return $result;
}
Daniel Kratohvil
  • 1,253
  • 15
  • 14