Is it possible to prefill/extend fields in a page object?

Let’s say I have a $page object with text and theme fields. I pass that object to a snippet and use the fields like this:

In the template:

snippet('my-snippet', ['page' => $myPage]);

In the snippet:

$page->text()->value();
$page->theme()->value();

My question is - is there a way to overwrite the text or theme values of $myPage before it’s passed to the snippet? I want to do something like this:

if ($condition === true) {
	$myPage->text = 'foo bar';
	$myPage->theme = 'dark';
}

snippet('my-snippet', ['page' => $myPage]);

Since Kirby’s objects are immutable, how would I do that?


My goal is to be able to alter field values in PHP and have the snippet use them as if those were the original values.

What kind of information do you need aside from those fields? It might make sense to create a completely new page object: https://getkirby.com/docs/reference/objects/page/__construct

You could do this in a page model, or maybe create new field objects, not tested.

I guess I could use $page->clone(). It doesn’t have to be the same object. To quote myself:

My goal is to be able to alter field values in PHP and have the snippet use them as if those were the original values.

If the cloned page object would function the same way as the original one, except with different field values - then I guess $page->clone() would do the job. I’m looking for a solution that wouldn’t lead to unexpected behavior.

If you use

$myPage = $page;
if ($condition === true) {
	$myPage->text = 'foo bar';
	$myPage->theme = 'dark';
};

snippet('my-snippet', ['page' => $myPage]);

you should get, what you want.

This won’t work for properties of the object like the title.

Then add the needed fields in the array of the snipped call if need…
The rest has to be coded in the snippet.

@hdodov is asking for an easier, cleaner method where he doesn’t have to change the actual snippet code and add multiple conditions there.

I guess cloning the page object or using a page model to conditionally overwrite the fields globally would be the way to go.

That is not my way, because afterwards it is for me like voodoo…
I cannot see the code, where it is working.

I know, that is more modern, but at my age I follow, what I can understand after let me say some months…