How can I write to nested structure fields with a hook?

Hi there,

I am trying to write to a specific field within structure fields that are themselves nested with parent structure fields (this all refers to building blocks set up with the kirby-builder plugin, but I figured behind the scenes they are just structure fields).

Following some other forum posts I was able to write to field in the parent structure field like so:

// config.php

'page.update:after' => function ($page) {
  $yamlbuilder = $page->mybuilder()->yaml();
  foreach ($yamlbuilder as &$block) {
    $block['testfield'] = 'my test string';
  }

  $page->update([
    'mybuilder' => Data::encode($yamlbuilder, "yaml"),
  ]);
}

This works, but now each of these blocks has another structure (builder) field within and I need to write to a field within this child structure fields blocks.

So I figured it would be something like this:

$yamlbuilder = $page->mybuilder()->yaml();
foreach ($yamlbuilder as &$outerblock) {
  $outerblock['testfield'] = 'outer test string';

  $yamlinnerbuilder = $outerblock['innerbuilder']->yaml();
  foreach ($yamlinnerbuilder as &$innerblock) {
    $innerblock['innertestfield'] = 'inner test string';
  }
}

But this gives me an error Call to a member function yaml() on array. I guess I am missing some encoding/decoding step somewhere, but I can’t figure it out.

Could anybody help me with this? Thanks!

<?php 

$yamlbuilder = $page->mybuilder()->yaml();

foreach ($yamlbuilder as &$outerblock) {
  $outerblock['testfield'] = 'outer test string';

  foreach ($outerblock['innerbuilder'] as $key => &$value) {
    
    $value = 'inner test string';
  }
}
dump($yamlbuilder);

This does not seem to work. Where would I need to reference the name of my inner field (innertestfield) in this? It currently runs without error, but it does not write the test string to any field.

Ah, I left out the key:

<?php 

$yamlbuilder = $page->mybuilder()->yaml();

foreach ($yamlbuilder as &$outerblock) {
  $outerblock['testfield'] = 'outer test string';

  foreach ($outerblock['innerbuilder'] as $key => &$value) {
     $value['innertestfield'] = 'inner test string';
  }
}

Works flawlessly.
Thank you so much!