Create custom blocks programmatically

Thanks a lot for looking into this and for the help.
As for a kirby noob like me this answer is not fully complete, I post my code here to maybe help someone in the future:

A prerequisite for this to work is, that you override the image.yml:

and add a url property only then it can be set.

Also the part of how to convert it to an array is missing. As I did not know there is a kirby method for that I needed to find out first:

<?php

Kirby::plugin('seriamlo/mh-image-block', [
  // we dont need any blueprints, as this plugin just adds a hook to change image blocks
  'hooks' => [
    'page.update:after' => function ($newPage, $oldPage) {
        $newBlocks = new Kirby\Cms\Blocks();
        $blocks    = $newPage->teaserText()->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,
                'alt'      => $block->alt()->value(),
                'caption'  => $block->caption()->value(),
                'url'  => $url,
                'link'     => $block->link()->value(),
              ],
              'id'   => $block->id(),
              'type' => $block->type()
            ],
            );
            $newBlocks->add($newBlock);
        }
        endforeach;

      $newPage->update([
        'teaserText' => $newBlocks->toArray(),
      ]);
    }
  ]
]);

Hope this helps somebody.
And thanks a lot for helping out on sundays! Appreciate it a lot!
:raised_hands:


Just a last question, because the title of this thread is Create custom blocks programmatically. I assume this will now also work with custom block types, right?

If I can I will try it out, but right now I need to proceed a bit as I have waisted some time getting here.

1 Like