kirby-json-api
kirby-json-api copied to clipboard
Get custom fields?
Hi @lord-executor, and thanks for your work!
Here is my problem, I try to build a custom API, but I can't get custom fields (on files for this example).
if i have a blueprint like this:
files:
type:
- image
fields:
customcolor:
label: color
type: input
and a custom api like this:
public function getWorks($name)
{
$page = page($name);
if ($page === false)
return KirbyResponse::error('Page not found', 404, ['name' => $name]);
return JsonApiUtil::pageToNode($page)
->selectFields(['id', 'url', 'title', 'files'])
->mapField('files', function($field) use ($page) {
return JsonApiUtil::filesToJson($page)
->selectFields(['url', 'customcolor']); // here is the call to my custom field
});
}
the result is:
{
id: "THE_ID",
url: "THE_URL",
title: "THE_TITLE",
files: [
{
url: "THE_FILE_URL"
// the customcolor field should be here, but it's not...
}
]
}
I can get the url field of my files, but not the customcolor field, and dont understand why...
Any ideas?
Thanks!
ok that's because the plugin works only with string fields (for files), and not with object fields (and custom fields seems to be saved as objects in kirby?).
i've made a dirty fix to fit my needs, but if you have a better solution?
in JsonApiUtil.php:
public static function filesToJson($page, $fields = null)
{
if (empty($page)) {
return null;
}
$files = [];
foreach ($page->files() as $file) {
$collection = new JsonFieldCollection();
if ($fields) {
$file_fields = [];
foreach ($fields as $field) {
$file_field = $file->{$field}();
if ( is_string( $file_field ) ) {
$file_fields[$field] = new StaticField( $file_field );
}
if ( is_object( $file_field ) ) {
$file_fields[$field] = new StaticField( $file_field->value() );
}
}
$collection->addFields($file_fields);
} else {
$collection->addFields([
'url' => new StaticField($file->url()),
'name' => new StaticField($file->name()),
'extension' => new StaticField($file->extension()),
'size' => new StaticField($file->size()),
'niceSize' => new StaticField($file->niceSize()),
'mime' => new StaticField($file->mime()),
'type' => new StaticField($file->type()),
]);
}
$files[] = $collection;
}
return new JsonListCollection($files);
}