Update a structured field

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 ?!?!?

Are the values in these variables just strings or objects?

Just strings

:thinking:

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?

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!
:partying_face:

addToStructure($page, 'prices',[
	'type' => (string)$tickettype,
	'price' => (string)$price
]);

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.

You can set the field to null to remove everything:

$kirby->impersonate('kirby');
$page->update([
  'prices' => null,
]);

Unfortunately that doesn’t seem do do anything.
Not on a structured field like prices and also not on “normal” fields.
:cry:

Then try an empty string:

$kirby->impersonate('kirby');
$page->update([
  'prices' => '',
]);

Yes! Thank you Sonja! :partying_face: