Created
November 22, 2014 09:05
-
-
Save dljoseph/de44dce46b2194661381 to your computer and use it in GitHub Desktop.
SilverStripe 3.1.x add date range filters to modeladmin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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
It's April of 2019 and this gist is still providing value.