Filter by past dates in a query

Hi there,

I am using the k3-pagesdisplay-section plugin to list pages in a section. This list can be sorted via a query field in the blueprint. So far the sorting works fine:

query: page.children.sortby('mydate', 'asc')

However, now I would like to alter this query to filter out all the pages whose mydate is in the future. While I find an example of filtering past dates in the reference, it uses a custom function. I don’t know how to transfer this to a query.

Is this possible somehow? If so, how?

Thanks!

I’d create a custom pages method.

(Please use our fantastic categories to categorise your questions thanks!)

Ok, now I am majorly confused, how do I do this?
I tried this, but obviously it does not work. How can I pass on the $mydate var to the inner function?

Kirby::plugin('my/pagesMethods', [
  'pagesMethods' => [
    'filterPastDates' => function($mydate) {
      return $this->filterBy(function ($child) {
        return $mydate < time();
      });
    }
  ]
]);

(Ideally I want to be able to feed different date fields into the function, my page has fields like startdate, enddate etc.)

If you pass a callback, you have to use filter() not filterBy() and you have to call the method on the child:

Kirby::plugin('my/pagesMethods', [
    'filterPastDates' => function($mydate) {
      return $this->filter(function ($child) {
        return $child->{$mydate}()->toDate() < time();
      });
    }
  ]
]);

Hm, this gives me this error:

The section "mysection" could not be loaded: Undefined variable: mydate

I am supposed to use it as follows, right?

query: page.children.sortby('mydatefieldname', 'asc').filterPastDates('mydatefieldname')

Does it work if you hardcode the field in your method and to not pass the variable in the query?

Which Kirby version?

This should be like that?

Kirby::plugin('my/pagesMethods', [
    'pagesMethods' => [
        'filterPastDates' => function($mydate) {
            return $this->filter(function ($child) {
                return $child->{$mydate}()->toDate() < time();
            });
        }
    ]
]);
1 Like

Yes, hardcoded it works. However, that would mean I would need to write a method for each specific date field (I have multiple ones). I think the issue is in forwarding the $mydate argument into the inner function.

Yes, sorry, pasted it wrong initially. I had fixed that on my end already, still I get the error described above.

Again, what is your Kirby version?

Oh, sorry. Version 3.2.2

We missed use method:

Kirby::plugin('my/pagesMethods', [
    'pagesMethods' => [
        'filterPastDates' => function($mydate) {
            return $this->filter(function ($child) use ($mydate){
                return $child->{$mydate}()->toDate() < time();
            });
        }
    ]
]);
3 Likes

Oh, nice. Now it works!

Thank you so much @ahmetbora and @texnixe. Learned something new again about PHP and Kirby. :slight_smile: Solved!