Add method to append to structure field

Hi @bastianallgeier,

There is an option to update the page via frontend with $page->update(). This is great and works good.
In my case I use it to store signups from users for a birtdayparty into a structure-field. To add an item to the structurefield I have to get the whole field first, convert it to an array, appaned the new data to the array, convert back to yaml and then update the page.

it would be great to have something like:

$page->mystructure()->add(array( key => value));

(It would be even nicer, if the structure-field could be more like a database with something like add(), remove(), update() including something like

$page->mystructure->update(array(key2 => value2 ))->where( key, "=", value);

Just an Idea, but would be happy with the add() at first :wink:

Cheers, Jan

2 Likes

Hi Jan,

Would you mind posting more of the logic you’re using to update the structure field like this?

Was looking to do something similar and wasn’t sure if it makes sense to try doing this in a template or a controller.

Thanks!

Hi @scottswany

I was also looking for a way to update the structure field type outside via the front-end.

Here’s how I did it:

// this is the page which has the structure field type (called submissions in my case)
$submissions = site()->find('submissions');
// get existing entries in an array
$existing_submissions_array = $submissions->content()->get('submissions')->yaml();
// add a new entry to the array
$existing_submissions_array[] = ['name' => $form['name'], 'email' => $form['email'];
// update the structure field type
page('submissions')->update([
   'submissions' => yaml::encode($existing_submissions_array)
]);

The $form variable holds data submitted through a front-end form. It’s coming from the uniform plugin (https://github.com/mzur/kirby-uniform).

The whole code is placed in a custom action for the uniform plugin but you can also place it in a controller. I prefer the plugin way because it’s more solid. It has built-in validation, spam filter, and a lot of flexibility.

Hope this helps.

Also, @Jan thanks so much for the original post!!

2 Likes

Thanks @kyrpas! That looks like exactly what I needed.

Hi! Is there any option to give us a small look at the code you used? All of it :stuck_out_tongue: I am a Newbie and still figuring out how to do it. If so, thank you a lot!

Here is a little function to add an element to a structure field:

    /**
     * Add a new element to a kirby structure field
     * @param string $page
     * @param string $field
     * @param array $data
     */
    function addToStructure($page, $field, $data = array()){
      $fieldData = page($page)->$field()->yaml();
      $fieldData[] = $data;
      $fieldData = yaml::encode($fieldData);
      try {
        page($page)->update(array($field => $fieldData));
        return true;
      } catch(Exception $e) {
        return $e->getMessage();
      }
    }
2 Likes