How to Conditionally remove Block or Container from Layout programatically?
Asked Answered
R

2

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

Ranking answered 10/3, 2018 at 12:45 Comment(0)
R
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');
        }
    }
}
Ranking answered 12/3, 2018 at 6:58 Comment(0)
U
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;
}
Ut answered 11/2, 2019 at 10:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.