Yii2:如何在自定义ActiveDataProvider中进行过滤?

时间:2018-12-10 16:10:27

标签: filter yii2

我创建了这个ActiveDataProvider:

$dataProvider = new ActiveDataProvider([
    'query' => $query->asArray(), // It is a simple SQL query.
    'key' => 'item',
    'sort' => [
        'attributes' => [
            'item',
            'quantity',
        ],
    ]
]);

我需要为项目数量添加过滤器,因为它不起作用(无法搜索):

item and quantity filter don't work

1 个答案:

答案 0 :(得分:0)

您必须未在SearchModel safe方法中将属性项和数量设置为rules()

您必须在SearchModel中将它们设置为safe

public function rules()
{
    return [
        [['item', 'quantity'], 'safe'],
    ];
}

对于您来说,您的数据提供者应该像这样:

// It is not necessary to use "$query->asArray()", because your "$query" itself is object of ActiveQuery
    $dataProvider = new ActiveDataProvider([
        'query' => $query,
        'key' => 'item',
    ]);