Search code examples
phpyii2

Yii2 yii\data\ActiveDataFilter and pagination false


I have configured the yii2 restapi in module.

Now for setting pagination to false and to add filter I added the code like:

public function actions()
    {
        $actions = parent::actions();
        unset($actions['create'], $actions['update'], $actions['delete']);

    $actions['index'] = [
        'class' => 'yii\rest\IndexAction',
        'modelClass' => $this->modelClass,
        'checkAccess' => [$this, 'checkAccess'],

        'prepareDataProvider' => function () {

            $model = new $this->modelClass;
            $query = $model::find();

            $dataProvider = new ActiveDataProvider([
                'query' => $query,
                'pagination' => false,

            ]);
            return $dataProvider;
        },
    ]; 
    $actions['index']['dataFilter'] = [
        'class' => 'yii\data\ActiveDataFilter',
        'searchModel' => 'app\models\TimeTableSearch'
    ];
    return $actions;
}

but filtering doesn't work, but if I comment out or remove $action['index'] array, filtering works fine, but my setting of pagination false stops working.

how I can fix it.


Solution

  • You are not passing your filter to data provider. It should be something like this (not tested):

    'prepareDataProvider' => function ($action, $filter) {
        $model = new $this->modelClass;
        $query = $model::find();
        if (!empty($filter)) {
            $query->andWhere($filter);
        }
    
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => false,
    
        ]);
        return $dataProvider;
    },