Hello,
I’m struggling to represent a simple structure field in json, following Content representations | Kirby CMS
Here is my default.yml :
title: Default Page
preset: page
pages: false
fields:
mandalas:
label: Mandalas
type: structure
fields:
mandala_name:
label: Name
type: text
mandala_layers:
label: Mandala layers
type: files
multiple: true
layout: cards
and my incomplete default.json.php
<?php
$json = [];
$mandalas = $page->mandalas()->toStructure();
foreach($mandalas as $mandala) {
$json[] = [
'mandala_name'=> (string)$mandala->mandala_name(),
];
// Missing code to iterate through mandala_layers and output images URLs
}
echo json_encode($json);
Thanks for your help
That code should work. What exactly is the issue? Do you get an error message? Just nothing?
I wouldn’t cast to string but use value() to convert the field to a string, but that’s not the problem here.
'mandala_name'=> $mandala->mandala_name()->value(),
Thanks for your time @pixelijn.
The code above only outputs “mandela_name”. I’m asking for help to write the line of code that would iterate through and output the second field “mandala_layers” which would be a list of file urls (hence the “// Missing code to iterate through mandala_layers and output images URLs” in the code above).
Ah, ok.
foreach($mandalas as $mandala) {
$files = $mandala->mandala_layers()->toFiles();
$urls = [];
foreach($files as $file) {
$urls[] = $file->url();
}
$json[] = [
'mandala_name' => (string)$mandala->mandala_name(),
'mandala_layers' => $urls,
];
// Missing code to iterate through mandala_layers and output images URLs
}
1 Like