Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Data Model Questions /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Filter Records by a function on the model. [solved]


Go to End


4 Posts   2239 Views

Avatar
cumquat

Community Member, 201 Posts

16 May 2015 at 3:29am

Edited: 16/05/2015 3:30am

HI there,
This could just be a Friday brain drain but for the life of me i can't workout/remember how to filter a dataset using a function on the model. I have a Runner data model and i wish to return all runners thats easy

$runners = Runner::get();
return $runners

but the next stage is to only bring back runners that are overdue at their checkpoint so i have a function on the model.
public function RunnerOverdue() {
    $distance = self::NextCP();
    $thetime = strtotime(self::TheLKPtime());
    if($distance and self::Pace() > 0){
          $nexttime = (($distance / self::Pace()) * 60 * 60);
          $current = time();
          $next = $thetime + $nexttime;
          if($current > $next){
                $overDue = true;
          } else {
                $overDue = false;
         }
    return $overDue;
    } 
 }

So what i want to do is only return the Runners that have a RunnerOverdue = true

I did this before about 12-18 months ago and it worked, now it doesnt, the old code was

function getOverdue() {
        $runners = Runner::get()->filter('RunnerOverdue()' > 0);
        return $runners;
}

any help or pointers please?

Mick

Avatar
muskie9

Community Member, 24 Posts

16 May 2015 at 3:39am

cumquat, would this work:

function getOverdue() {
        $runners = Runner::get()->filter('RunnerOverdue()', 1);
        return $runners;
}

Avatar
kinglozzer

Community Member, 187 Posts

16 May 2015 at 3:43am

Edited: 16/05/2015 3:43am

Sounds like you’re looking for DataList::filterByCallback().

$runners = Runner::get()->filterByCallback(function($record) {
    return $record->RunnerOverdue();
});
return $runners;

Avatar
cumquat

Community Member, 201 Posts

16 May 2015 at 4:10am

Top banana, kinglozzer, you were spot on, not used that before. many thanks for your help there.

Also muskie9 thanks for that, i had tried that and it didn't work, but now have a solution. Thanks.

Much appreciated guys.

Mick