Adding pages to a page field programmatically

Hello everyone,

In my application users should have the possibility to favor certain pages. The user has received a “favorites list” in the yaml:

fields:
  favorites:
    type: pages

How can I add a page (via permalink) to this field? I have tried many things, but unfortunately none of them worked.

My last miserable attempt:

$user = $kirby->user();
$favorites= $user->favorites()->toPages();
$favorites->add(page('page://3hgC7B6br799ZJNC'));
$string = "";
  
foreach ($favorites as $page) {
    $string .= "- " . $page->permalink();

    if (!next($favorites)) {
        $string .= "\n";
    }
}

$user->favorites()->value($string);

Thank you very much for your help!
Best regards

I assume you want to update the favorites field in the user content here? Then you need to update the $user object ($user->update()), see $user->update() | Kirby CMS.

Thank you very much for your answer.
Unfortunately, this does not work quite as expected.
I can update the “test” field, but not my favorites list.

$favorites = $kirby->user()->favorites()->toPages();
$favorites->add(page('page://3hgC7B6br799ZJNC'));

$kirby->user()->update([
    'favorites' => $favorites,
    'test' => '123'
]);

Because you need to store an array of page ids or uuids, not a collection of pages.