2017-02-24 65 views
2

我在DataObject中有date-property。SilverStripe。在ModelAdmin中按日期范围搜索

如何在ModelAdmin中按日期范围进行搜索?

例如:“搜索所有项目,其中日期超过2007-13-01且小于2007-17-01”
或“搜索所有项目,其中日期2007-13-01和2007-17之间-01“

现在我只能使用GreaterTranFilter或LessThanFilter进行搜索,但不能同时使用这两种方法。

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 ...' 
     ], 
    ]; 
} 

另外搜索字段必须使用日历(日期选择器)

DateField: 
    default_config: 
    showcalendar: true 

你能举一个例子,如何按日期范围进行搜索吗?

+0

快速谷歌搜索显示我https://gist.github.com/dljoseph/de44dce46b2194661381哪些可能会帮助你 – wmk

回答

4

有一个WithinRangeFilter,但如果你只使用配置,它不会让你感觉很远。这是你真正需要实施的程序。

通过超载getSearchContext()添加范围过滤器,然后重载getList()并检查日期范围的请求参数q,并将它们应用于列表。

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($q['Start'])) { 
     $filters['Date:LessThanOrEqual'] = $q['Start']; 
    } 
    if(isset($q['End'])) { 
     $filters['Date:GreaterThanOrEqual'] = $q['End']; 
    } 

    return $list->filter($filters); 
}