Magento 2 – How to Get All Children Blocks in Controller

blockscontrollersmagento2

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

Thanks in advanced.

Best Answer

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);
  }

}