Skip to content

Instantly share code, notes, and snippets.

@dljoseph
Created November 22, 2014 09:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dljoseph/de44dce46b2194661381 to your computer and use it in GitHub Desktop.
Save dljoseph/de44dce46b2194661381 to your computer and use it in GitHub Desktop.
SilverStripe 3.1.x add date range filters to modeladmin
<?php
class MyDataObjectAdmin extends ModelAdmin {
private static $managed_models = array('MyDataObject'); // Can manage multiple models
private static $url_segment = 'my-data-object'; // Linked as /admin/my-data-object/
private static $menu_title = 'My DataObjects';
public function getSearchContext() {
$context = parent::getSearchContext();
$dateField = new DateField("q[FromDate]", "From Date");
// Get the DateField portion of the DatetimeField and
// Explicitly set the desired date format and show a date picker
$dateField->setConfig('dateformat', 'dd/MM/yyyy')->setConfig('showcalendar', true);
$context->getFields()->push($dateField);
$dateField = new DateField("q[ToDate]", "To Date");
// Get the DateField portion of the DatetimeField and
// Explicitly set the desired date format and show a date picker
$dateField->setConfig('dateformat', 'dd/MM/yyyy')->setConfig('showcalendar', true);
$context->getFields()->push($dateField);
return $context;
}
public function getList() {
$list = parent::getList();
$params = $this->request->requestVar('q'); // use this to access search parameters
if(isset($params['FromDate']) && $params['FromDate']) {
$list = $list->exclude('Created:LessThan', $params['FromDate']);
}
if(isset($params['ToDate']) && $params['ToDate']) {
//split UK date into day month year variables
list($day,$month,$year) = sscanf($params['ToDate'], "%d/%d/%d");
//date functions expect US date format, create new date object
$date = new Datetime("$month/$day/$year");
//create interval of Plus 1 Day (P1D)
$interval = new DateInterval('P1D');
//add interval to the date
$date->add($interval);
//use the new date value as the GreaterThan exclusion filter
$list = $list->filter('Created:LessThan', date_format($date, 'd/m/Y'));
}
return $list;
}
}
@tazzydemon
Copy link

Its official. You are brilliant. Documentation in this area is scant and confusing. I was working on getDefaultSearchContext to the data model. You code was exactly what I wanted.

IMHO the last filter should perhaps be LessThanOrEqual as you will likely require dates including the end one.

@sageworksstudio
Copy link

It's April of 2019 and this gist is still providing value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment