问题
I have date-property in my DataObject.
How can I search by date-range in ModelAdmin?
For example: "search all items where date is more than 2007-13-01 and less than 2007-17-01"
or "search all items where date is between 2007-13-01 and 2007-17-01"
For now I can search only with GreaterTranFilter or with LessThanFilter, but not with both.
class MyObject extends DataObject {
private static $db = [
"Date" => "Date",
];
private static $summary_fields = [
"Date" => "Date",
];
private static $searchable_fields = [
"Date" => [
"field" => "DateField",
"filter" => "GreaterThanFilter",
"title" => 'Date from ...'
],
];
}
Additionally search field must use a calendar(datepicker)
DateField:
default_config:
showcalendar: true
Can you give an example how to search by date-range?
回答1:
There is a WithinRangeFilter
, but it's not going to get you very far if you're using configuration only. This is something you really need to implement procedurally.
Add the range filters by overloading getSearchContext()
, then overload getList()
and check the q
request param for the date ranges, and apply them to the list.
public function getSearchContext()
{
$context = parent::getSearchContext();
$context->getFields()->push(DateField::create('q[Start]','Start'));
$context->getFields()->push(DateField::create('q[End]','End'));
return $context;
}
public function getList()
{
$list = parent::getList();
$params = $this->getRequest()->requestVar('q');
$filters = [];
if(isset($params['Start'])) {
$filters['Date:LessThanOrEqual'] = $params['Start'];
}
if(isset($params['End'])) {
$filters['Date:GreaterThanOrEqual'] = $params['End'];
}
return $list->filter($filters);
}
来源:https://stackoverflow.com/questions/42440841/silverstripe-search-by-date-range-in-modeladmin