Add/remove favourite pages in user account via frontend

Hi guys,

is it possible to add and remove “favourite” pages to a user account and display them on the user page?

example: user is logged in and can add the current page to his account.

From the front-end rather then the backend, you mean? Frontend: You could implement a button that then calls a route via Ajax, that then stores the information in the user file-

1 Like

Yep, I almost got it running like this, there is just a little problem left:
I need to add multiple sites, but so far it only overwrites one entry.

my page:

<?php snippet('header') ?>
<main class="main">
    <h1><?= $page->title()->html() ?></h1>

    <?php if (isset($alert['error'])): ?>
    <div><?= $alert['error'] ?></div>
    <?php endif ?>
    <form method="post" action="<?= $page->url() ?>">
        <input type="submit" name="submit" value="Zur Sammlung">
    </form>
</main>

<?php snippet('footer') ?>

<?php

if($kirby->request()->is('POST') ) {
            $kirby->user()->update([
              'Sammlung' => $page,
            ]);
            echo 'Zur Sammlung hinzugefügt';
                
};?>

Blueprint field:

fields:
  Sammlung:
    type: pages

The overwritten field looks like this:

That’s because you simply overwrite your field value with the new page.

What you would have to do is to first get the stored values, then add/remove the selected entry, then update the user with the result. Note that a pages field stores entries in yaml format.

Append the element:

$storedValues = $user->sammlung()->toPages();
$result = $stored->append($page);

$user->update([
  'sammlung' => data::encode($result->toArray(), 'yaml')

]);

Remove the element:

$storedValues = $user->sammlung()->toPages();
$result = $stored->not($page);

$user->update([
  'sammlung' => data::encode($result->toArray(), 'yaml')

]);

This is just the basic procedure. You might want to add some checks if the new element is already stored or if the element to remove is actually stored before updating, wrap the update in a try-catch block to throw an error if the update is not successful etc.