11

I have to get all children block in controller using parent block name or layout Magento 2.

Thanks in advanced.

2 Answers 2

7

Make sure your controller is same which loads the layout in which your block and its child blocks exits.


use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

class Edit extends \Magento\Backend\App\Action
{
  protected $resultPageFactory;

  public function __construct(
       Context $context,
       PageFactory $resultPageFactory
  ){
       $this->resultPageFactory = $resultPageFactory;
       parent::__construct($context);
  }

  $resultPage = $this->resultPageFactory->create();

  $blockInstance = $resultPage->getLayout()->getBlock('your.block.name');

  $childBlocks = $blockInstance->getChildNames();

  foreach($childBlocks as $blockName){
    $block = $resultPage->getLayout()->getBlock($blockName);
  }

}
3
  • 1
    saras amithsing nice answer. May 15, 2017 at 6:07
  • It's working fine for me Thanks @ Amit Singh Jun 2, 2017 at 7:17
  • @AmitSingh, Please explain, $blockInstance->getChildNames(); here getChildNames() means? Oct 12, 2018 at 5:12
0

You can get all child blocks like this.

$allblocks = $block->getChildNames();

  foreach($allblocks as $blocks){
    $child_block = $this->resultPageFactory->create()->getLayout()->getBlock($blocks);
  }
1
  • I have tried all that function which is used to get child blocks but it's not working. May 17, 2017 at 4:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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