如何在控制器Magento 2中获得所有子块?


Answers:


7

确保加载加载块及其子块退出的布局的控制器相同。

使用Magento \ Backend \ App \ Action \ Context;
使用Magento \ Framework \ View \ Result \ PageFactory;

类Edit扩展\ Magento \ Backend \ App \ Action
{
  受保护的$ resultPageFactory;

  公共功能__construct(
       上下文$ context,
       PageFactory $ resultPageFactory
  ){
       $ this-> resultPageFactory = $ resultPageFactory;
       父母:: __ 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);
  }

}

1
萨拉斯回答很好的答案。
拉克什·耶萨迪亚

对我来说很好,谢谢@ Amit Singh
Dharmendra Jadav

@AmitSingh,请解释一下,$blockInstance->getChildNames();这里的getChildNames()是什么意思?
Payal Patel

0

您可以像这样获得所有子块。

$allblocks = $block->getChildNames();

  foreach($allblocks as $blocks){
    $child_block = $this->resultPageFactory->create()->getLayout()->getBlock($blocks);
  }

我已经尝试了所有用于获取子块的功能,但无法正常工作。
Dharmendra Jadav's
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.