Structured fields from frontend

I’ve been looking at the structured fields and was wondering whether it’s possible to append new data into a structured field from the frontend.

Previously I’ve created a whole new admin separate from thenkirby panel for frontend users to log in and update information but what if this information was saved from a form to a structured field?

Is this possible? I’m afraid I’m away from a computer and using my phone to ask this question so can’t properly scan the docs.

Any help would be appreciated!

Thanks

1 Like

Yes, that’s possible, have a look at this post: Add method to append to structure field

Here is a function from that thread:

    /**
     * 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();
      }
    }

Thanks for this @texnixe. I’m struggling a bit to implement this though, How would the update function work with a form for example?

Haven’t tested it, but that I would do, i.e. standard form handling:

  • put the code in your action script that is called on submit
  • check if your form data is valid
  • if form data is valid, call the addToStructure function with the variables from the form

But maybe your problem is more specific?

Calling this function I get an error message:

Fatal error: Call to a member function sfc() on boolean in /path/to/template.php in line XX

Where sfc is the Structured Field Content field I’d like to addd something. I called the function in this way:

<?php addToStructure('page-uri', 'sfc', $data = array('some-field' => 'some-data')); ?>

Im sure it is some minor bug, but I can’t get him fixed.

This most likely means that the Page URI you passed is invalid.

I used the above code and it works fine :smile:

This is what I ended up with:

 <?php if(r::is('post')): ?>
      <?php addToStructure($page->uri(), 'comments', array("user" => strip_tags(get('user')), "timestamp" => strip_tags(get('timestamp')), "name" => strip_tags(get('name')), "email" => strip_tags(get('email')), "comment" => strip_tags(get('comment')))); ?>
 <?php endif ?>

Sorry, my fault: I’ve send the page’s UID instead of the URI to the function.

NoobYves