/ yii2

yii2-search

如何设置默认搜索条件?

class OrderSearch extends Order
{
    public function search($params)
    {
        ...
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            // 添加默认排序
            'sort' => [
                'defaultOrder'=> [
                    'orderid' => SORT_DESC
                ]
            ],
            // 自定义分页
            'pagination' => [
                'pageSize' => 15,
            ]
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            ...
        ]);

        // 设置默认搜索条件
        if(is_null($query->where)){
             $this->month = date('Y-m');
             $query->andFilterWhere(['month', $this->month]);
        }

        // 没有被填充的属性均为 null,设置默认搜索条件
        if (is_null($this->status)){
            $query->andFilterWhere(['>', 'status', 0])
                ->andFilterWhere(['<', 'status', 10]);
        } else {
            $query->andFilterWhere([ 'status' => $this->status]);
        }
    }
}

按时间搜索

View _search.php

use yii\jui\DatePicker;

<?= $form->field($model, 'created_at')->widget(DatePicker::className(),['dateFormat' => 'yyyy-MM-dd'])
        ->textInput(['placeholder' => '一个月之内的'])?>

SearchModel OrderSearch.php

class OrderSearch extends Order
{
    public function rules()
    {
        return [
            ...
            [['created_at', 'updated_at'], 'date', 'format'=>'yyyy-MM-dd', 'message'=>'{attribute} 格式必须为 yyyy-MM-dd'],
        ];
    }

    public function search($params)
    {
        ...
        if ($this->created_at){
            $current = strtotime($this->created_at);
            $future = strtotime('+1 month', $current);
            $query->andFilterWhere(['>=', 'created_at', $current])->andFilterWhere(['<', 'created_at', $future]);
        }
        ...
    }
}