filterBy pages field plus sortBy desc in structure field

Hi! I read the filter compendium however, I can’t figure out to make the following structure field filtering work.

The structure field contains a single select pages field. A hidden field inside the structure field is being populated with a hook called (unix).
I’m trying to desc sort the entries of the structure field by the hidden unix field BUT filter them first by a certain title or uid of the pages field. The pages blueprint entry is called eventdetailpage.

$title = "Some title";
$events = page("events")->events()->toStructure();
$events_filtered_by_title = $events->event_detail_page()->toPages()->filterBy("title", $title);
      
$events_sorted = $events_filtered_by_title->sortBy(function ($page) {
   return $page->unix();
}, 'desc');
 
foreach($events_sorted as $event):

It gives a toPages() error – am I using the toPages() wrong?

Yes, you will have to use a filter method with a callback and call the toPage() method inside on a single structure element.

Would a dirty if-clause inside the foreach loop be slower than the “correct” way (the one you suggested)? Because I’m not that skilled in PHP.

$events_sorted = $events_filtered_by_title->sortBy(function ($page) {
   return $page->unix();
}, 'desc');

foreach($events_sorted as $event):
    if ($event->event_detail_page()->toPage()->uid() == $page->uid()){
        etc.
    }
$title = 'Some title';
$events = page("events")->events()->toStructure();
$events_filtered_by_title = $events->filter(function($event) use($title) {
  if ( $p = $event->event_detail_page()->toPage() ) {
    return $p->title() === $title;
  }
});
1 Like

Thanks @texnixe, I’ll try that! Thx!

I had an error above, the p was missing, corrected now.

1 Like