🚀 A new era: Kirby 4 Get to know
Skip to content

Add blocks to blocks field programmatically

If you want to update a blocks field programmatically, e.g. with data from a frontend form, you can do it with the following code:

$blocks = $page->text()->toBlocks();

$text = new Kirby\Cms\Block([
  'content' => [
    'text' => '<p>Hug them if you like. They might not appreciate it though.</p><p>Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vestibulum id ligula porta felis euismod semper. Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod.</p>',
  'type' => 'text',

$heading = new Kirby\Cms\Block([
  'content' => [
    'text'  => 'This is a heading',
    'level' => 'h2',
  'type' => 'heading',

$quote = new Kirby\Cms\Block([
  'content' => [
    'text'     => 'Time flies like an arrow; fruit flies like a banana',
    'citation' => '<a href=\"https://en.wikipedia.org/wiki/Anthony_Oettinger\" rel=\"noopener noreferrer nofollow\">Anthony Oettinger</a>',
  'type'     => 'quote',
  'isHidden' => false,

$blocks = $blocks->add(new Kirby\Cms\Blocks([$heading, $text, $quote]));


  'text' => json_encode($blocks->toArray()),

The fields in the content array depend on the block type.

If you want to store human readable JSON, set the pretty option in your blueprint:

    type: blocks
    pretty: true

More about the blocks field