MinmlCo
November 16, 2015, 7:24pm
1
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
texnixe
November 16, 2015, 7:29pm
2
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();
}
}
MinmlCo
November 20, 2015, 2:04pm
3
Thanks for this @texnixe . I’m struggling a bit to implement this though, How would the update function work with a form for example?
texnixe
November 20, 2015, 2:20pm
4
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?
yves
November 24, 2015, 11:25am
5
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.
MinmlCo
November 24, 2015, 3:54pm
7
I used the above code and it works fine
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 ?>
yves
November 27, 2015, 5:43pm
8
Sorry, my fault: I’ve send the page’s UID instead of the URI to the function.
NoobYves