Create custom blocks programmatically

Ok, I played around a bit more, and it seems to work when I convert the blocks to array when updating the page:

$newBlocks = new Kirby\Cms\Blocks();
$blocks    = $page->text()->toBlocks();
foreach ($blocks as $block) :
  if ($block->type() !== 'image') {
    $newBlocks->add($block);
  } else {
    $url      = $block->image()->toFile()->url();
    $images   = $block->image()->toFiles()->pluck('filename');
    $newBlock = new \Kirby\Cms\Block(
      [
        "content" => [
          'location' => 'kirby',
          'image'    => $images,
          'url'      => $url,
          'alt'      => $block->alt()->value(),
          'caption'  => $block->caption()->value(),
          'link'     => $block->link()->value(),
        ],
        'id'   => $block->id(),
        'type' => $block->type()
      ],
    );
    $newBlocks->add($newBlock);
  }
endforeach;

$page->update(
  [
    'text' => $newBlocks->toArray(),
  ]
);

In the example above I added a new url field to the image block blueprint to store the url of the image.

2 Likes