Sort by optional field only when it is filled out

I’ve got two date fields, one of which is required to be filled out, while the other one is optional (and currently only shows up when a toggle field is flipped).

The trouble is that when querying the respective pages in the frontend, the optional field needs to take priority over the required one only if it is filled out.

Theoretically, two solutions come to my mind, but I’m unsure about how to best implement either:
1.: Is it possible to conditionally fill the value from the required field to the optional one in the panel when a page is saved? This would enable me to sort the pages by the optional field exclusively in the frontend.
2.: If the panel doesn’t support this functionality (and if it can’t be added via a hook, f.e.), another option would be to deal with this problem in the frontend query: Can I pass a function to the query that would sort the current page depending on which field is filled out?

Or am I missing a third, simpler solution? : )

Thank you! : )

Two options:

Try sorting by optional, then required

$sortedPages = $pages->sortBy('optional', 'desc', 'required', 'desc');

If that doesn’t yield the desired result (not sure how Kirby handles empty values in this case), then you can pass a callback to the sortby() method that checks if the field is filled and then returns this value, otherwise the other one.

Thank you for the quick reply!

The first option doesn’t work; I had already tried this and the sorting algorithm put all the elements with empty optional fields in one sequence infront of the elements with filled out fields.

I’ll look into the callback function. Thanks! ; )

$sortedPages = $pages->sortBy(function($item) {
    if ( $item->optionalDateField()->isNotEmpty() ) {
        return $item->optionalDateField()->toDate();
    }
    return $item->requiredDateField()->toDate();
}, 'desc');

Oh, wow - you already did that for me; that’s very helpful! ; )
Thanks a bunch!