2

I want to remove some items from a page when certain conditions apply. I got a solution but I'm wondering if there isn't any better way to do this.

Now the code that I have is for each block that I want to remove:

 protected function _toHtml() {
    if ($condition) {
      return '';
    }

    return parent::_toHtml();
 }

Now I was wondering if ther is a way to remove a container from the layout file instead of doing this for every block inside a single container. I tried something like this but it does not work:

protected function _toHtml() {
    if ($condition) {
      $this->getLayout()->removeOutputElement('container.name.in.layout');
      return '';
    }

    return parent::_toHtml();
  }

Anyone know's how to remove containers form the layout page within a block class, thanks.

1 Answer 1

2

You can try something like this,

$myXml = '<referenceContainer name="container.name.in.layout" remove="true"/>';
$layout = $this->getLayout();
$layout->getUpdate()->addUpdate($myXml);
$layout->generateXml();

Or you can call an observer class on layout_generate_blocks_before event and add below code in observer

    $layout = $observer->getLayout();
    $block = $layout->getBlock('container.name.in.layout');

    if ($block) {
        //you can apply or add you condition here.
        $layout->unsetElement('container.name.in.layout');
    }

First code also work in Observer just need to change this line $layout = $this->getLayout(); to $layout = $observer->getLayout();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.