Hello everyone,
so I have this collection from a locator field:
$location = $entry->locator()->toLocation();
dump( $location->content() );
Output:
Kirby\Cms\Content Object
(
[lat] => 18.96667
[lon] => 72.83333
[number] =>
[city] =>
[country] => India
[postcode] =>
[address] => Mumbai
)
All I want to do is to add for example the following at the end of this:
[mykey] => My Value
So then I’ll be able to use it like:
$location->mykey()
But how?
Thank you!
Where do you want to fill in the additional field? 1) In the panel, so that a user can manually enter a value? Or 2) automatically after saving so that it is stored to the content file? Or 3) when the website is being rendered, e.g in a controller?
And if 3), do you want to use field methods with this new field? Or is it enough to just have the field values?
In my case it’s:
- when the website is being rendered, e.g in a controller
and
Field methods would be cool, but just having the value would also be good.
I just tried this, but it seems to erase the keys 
$location = $entry->locator()->yaml();
$location['mykey'] = 'My Value';
$location = new Collection($location);
Having the bare values would be quite easy:
$location = $page->locationField()->yaml();
$location['new-field'] = 'New Value';
dump( $location );
it seems to erase the keys 
Collections don’t have keys, they are just lists of items, not key => value pairs.
Instead of creating a new Collection, maybe you can just update the Content:
$location = $page->locationField()->toLocation();
$location = $location->update(['new-field' => 'New value']);
I think i will just go with an associative array as you suggested here. That’ll work for me. I still wonder though if there’s a cool and easy way to add entries to a kirby collection.
Thanks!
The result of $entry->locator()->toLocation(); is not a collection object but a Kirby\Cms\StructureObject object, i.e. a single element in a Kirby\Cms\Structure Object.
And if you call $location->content() you end ob with a Kirby\Cms\Content object, which is not a collection type object either.
In general, objects are immutable in Kirby, which means they cannot be changed. But of course, you can create new objects, for example:
$location = $entry->locator()->toLocation();
// get the content object from the StructureObject object and convert to array
$content = $location->content()->toArray();
// add an item to the array
$content['mykey'] = 'somekey';
dump($content);
// create new content object from that array
$content = new Kirby\Cms\Content($content);
dump($content);
// then you can echo the field object like normal
echo $content->mykey();
If this has any advantage for your use case over just using the array, that's something you have to decide.