Add Composer Control Output Block Pragrammatically

220 Views Asked by At

I'm creating pages programmatically and inserting content to a Content Block but after it has been created, I can't edit it via composer (because it's not a core_page_type_composer_control_output, it's a regular content block). Is there a way to add a block to a page programmatically and have it play nice in Composer?

Relevant code I'm using:

$page = Page::getByPath('/articles/xxx');
$block = BlockType::getByHandle('content');
$data = array(
    'content' => 'the content',
);
$page->addBlock($block, 'Main', $data);
1

There are 1 best solutions below

0
Jozzeh On

To achieve this, I would setup the pagetype as you would create the page with composer.
(add the content block to composer and the standard output of the pagetype)

After creating the page, you will notice the composer-linked content block is present on the page but completely empty. Then I would update the block instead of trying to create a new block in the 'Main' area.

Code example (not tested):

$page = Page::getByPath('/articles/xxx');
$blocks = $page->getBlocks('Main');
if(!empty($blocks)){
  foreach($blocks as $block){
    //check if the blocktype is content
    if($block->getBlockTypeHandle() == 'content'){
      //we are pretty sure this is the content block in the main area
      //because it's the only content block present... updating the block content
      $data = array(
                'content' => 'the content',
              );
      $block->update($data)
    }
  }
}