Sort users on a page, by calculated value

Hi,

I am trying to display a list of users on a page. These need to be sorted by a calculated value, which comes from two dates in the user content file.

I can display the value I want to use by individual user like this:

$delta = 
  $kirby->user()->found()->toStructure()->last()->scanned()->toDate() - $kirby->user()->found()->toStructure()->first()->scanned()->toDate()

But now I need to do a “leaderboard”, which needs to be sorted like this (pseudo code to show what I mean):

$leaderboard = $users->filterBy('role','entrant')->sortBy({$delta calculated as above})

What is the best way of approaching this? Thanks for any guidance.

This cookbook recipe should help you: Sorting collections | Kirby CMS, I think using a user method would be best in this case.

Hi,

Super, thanks for the steer. A user method was just the thing, this is what I did:

<?php
Kirby::plugin('mhd/user-methods', [
    'userMethods' => [
        'delta' => function () {
            // calculated seconds duration from first to last date in structure
            return $this->found()->toStructure()->last()->scanned()->toDate() - $this->found()->toStructure()->first()->scanned()->toDate();
        }
    ]
]);
?>