Creating Image Blocks programmatically

Moin everybody!

I’m trying to convert a rather old kirby page to a new version with blocks instead of kirbytext fields. As the most pages are not that complex, I’m using Blocks::parse() for that. This works good except with images.

parse is creating image blocks but obviously referecing them with a web location an with the mediaUrl.

So I thought of just rewriting that block to a kirby location but I’m not getting behind this. My last approach was rather “harsh” because I thought there might be some problems when using update() on a blocks content but… it’s not working that way:

		$block = $oldBlock->toArray();
		if ($block['type'] == 'image') {
			$url = explode('/', $block['content']['src']);
			$block['content']['location'] = 'kirby';
			$block['content']['image'] = [A::last($url)];
			$block['content']['src'] = '';
		}
		$modifiedBlocks->add(Block::factory([
			'content' => $block['content'],
			'type' => $block['type'],
		]));

Are there any caveats when creating a image block programmatically? How should I reference an image when doing so?

Thanks!
Markus

An image block looks basically like this:

$image = new Kirby\Cms\Block([
  'content' => [
    'location' => 'kirby',
    'image' => [
      "dark-forest.jpg"
    ],
  ],
  'type' => 'image',
]);
$blocks = $page->text()->toBlocks();
$blocks = $blocks->add(new Kirby\Cms\Blocks([$image]));
$kirby->impersonate('kirby');

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

Thanks, Sonja!

I fed the $page->update() with the blocks collection because I thought Kirby would handle this directly. I now converted the collection to an array, did an json_encode and now every works like it should.

Yes, the strange thing is that I wrote a recipe that works with just the blocks in the past, as if something changed in the meantime. Have to check this and adapt the recipe if necessary.

Hi.

Indeed, the recipe did’nt mentionned the json_encode($blocks->toArray()), which seem necessary. Thanks !

Ok, I finally got round to dumping the recipe code into a Starterkit and it worked like advertised without me having to json_encode() the blocks.

Hm, the problem seems to be that it stops working when trying to add image to the mix.

I fixed the recipe.