Skip to content

Instantly share code, notes, and snippets.

@ryanwachtl
Forked from dljoseph/SS-modelAdmin.php
Created January 16, 2016 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanwachtl/331eaf57853dc05d238e to your computer and use it in GitHub Desktop.
Save ryanwachtl/331eaf57853dc05d238e 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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment