phpgridviewyii2yii2-basic-appdataprovider

Can we remove some records from Active Data provider before passing to grid view?


I am facing issue with a scenario that I have to show data in two different grids present on same view. I don't want to query separately for both grids. What I want to achieve is to query only once and split data for both grids separately and pass it to both grids. I have the option to hide rows on type basis but I don't want to use this

I have tried the option to hide rows on type basis but I don't want to use this option. I want something to split the main data provider into two data providers


Solution

  • The only way to do that with yii\data\ActiveDataProvider is extending it and overriding its prepareModels() and prepareKeys() methods.

    Other option is to use yii\data\ArrayDataProvider instead.

    //simple query just for illustration, modify it as you need
    $all = MyModel::find()->all(); 
    $first = $second = [];
    foreach ($all as $item) {
        // condition to decide where the current item belongs
        if (someCondition) { 
            $first[] = $item;
        } else {
            $second[] = $item;
        }
    }
    $firstProvider = new  \yii\data\ArrayDataProvider([
        'allModels' => $first,
    ]);
    $secondProvider = new  \yii\data\ArrayDataProvider([
        'allModels' => $second,
    ]);
    

    The main disadvantage of using ArrayDataProvider is, that you have to load all models into array even if you plan to use pagination. So if there are many rows in your table, it might be better to use two independent ActiveDataProvider and let them load the data in two queries.