rowdy
December 17, 2023, 10:57am
1
Hi,
I can’t get a structured update/insert working.
I’ve looked into the forum and tried various solutions, but to no avail unfortunately.
I get price data from an API and try to insert this into a structured field.
Blueprint:
fields:
prices:
label: Prijzen
type: structure
disabled: true
fields:
type:
label: Type
type: text
price:
label: Prijs
type: text
PHP code:
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();
}
}
// data from API
$tickettype = $priceSet->TicketType; // Team ticket
$price = $priceSet->Price; // 15.0000
// trying to insert
addToStructure($page, 'prices',[
'type' => $tickettype,
'price' => $price
]);
Result:
----
Prices: - [ ]
----
Expected result:
----
Prices:
-
type: Team ticket
price: 15.0000
----
What am I doing wrong ?!?!?
texnixe
December 17, 2023, 11:12am
2
Are the values in these variables just strings or objects?
texnixe
December 17, 2023, 11:21am
4
The code should work, and you don’t seem to get an error, so I guess at one point you also have the code to authenticate?
Your code is a bit out of context, maybe the issue is not in the part that your are showing.
If you just test out of any loop or so
$kirby->impersonate('kirby');
addToStructure($page, 'prices',[
'type' => 'Team ticket',
'price' => '15.99'
]);
does that do anything?
rowdy
December 17, 2023, 12:49pm
5
Yes, it did!
I was convinced it were just strings, because I could also simply echo
them.
But doing gettype($tickettype)
resulted in object
instead of string
to my big surprise.
So I changed the code to the following and it works.
Thanks!
addToStructure($page, 'prices',[
'type' => (string)$tickettype,
'price' => (string)$price
]);
rowdy
December 17, 2023, 2:04pm
6
Hi @texnixe a follow-up question.
addToStructure
adds the data to the structured field over and over again.
----
Prices:
-
type: Team ticket
price: "15.0000"
-
type: '10% Vroegboekkorting per team'
price: "13.5000"
-
type: Team ticket
price: "15.0000"
-
type: '10% Vroegboekkorting per team'
price: "13.5000"
-
type: Team ticket
price: "15.0000"
-
type: '10% Vroegboekkorting per team'
price: "13.5000"
----
How can I clear out the current yaml contents of prices
first?
I was looking for something like $page->prices()->remove()
, but it doesn’t seem to exist.
I’m using Kirby 3 BTW.
texnixe
December 17, 2023, 3:02pm
7
You can set the field to null to remove everything:
$kirby->impersonate('kirby');
$page->update([
'prices' => null,
]);
rowdy
December 17, 2023, 4:16pm
8
Unfortunately that doesn’t seem do do anything.
Not on a structured field like prices
and also not on “normal” fields.
texnixe
December 17, 2023, 4:20pm
9
Then try an empty string:
$kirby->impersonate('kirby');
$page->update([
'prices' => '',
]);