How to Programatically Add Entries to Structure Field

This is what I do in cases like this:

$states = $page->states()->yaml();

$states[] = [
  'abbr' => 'SP',
  'name' => 'São Paulo',
  'capital' => 'São Paulo'
];

$page->update([
  'states' => Yaml::encode($states)
]);

It would be cool to have a field method to simplify this process:

$page->states()->addToStructure([
  'abbr' => 'SP',
  'name' => 'São Paulo',
  'capital' => 'São Paulo'
]);

EDIT: Since I need this one for myself a lot, here you go:

<?php // site/plugins/site/index.php

use Kirby\Cms\Field;

Kirby::plugin('site/methods', [
  'fieldMethods' => [
    'addToStructure' => function (Field $field, array $entry): void {
      $value = $field->yaml();

      if (isset($entry[0]) && is_array($entry[0])) {
        array_push($value, ...$entry);
      } else {
        array_push($value, $entry);
      }
      
      $field->parent()->update([
        $field->key() => Yaml::encode($value)
      ]);
    }
  ]
]);

EDIT 2: Just updated the method to allow adding multiple entries at once:

$page->states()->addToStructure([
  [ 'name' => 'Goiás' ],
  [ 'name' => 'São Paulo' ],
]);
6 Likes