Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2. How to set scenario in dataProvider?

Tags:

yii2

I want to return different fields depends on scenario. How can I set it in dataProvider?

$query = User::find();
$activeData = new ActiveDataProvider([
    'query' => $query,
    'pagination' => [
        'pageSize' => 10,
     ],
]);

Fields in User model:

public function fields()
{
    if ($this->scenario == 'statistics') {
        return [
            'id',
            'email',
            'count'
        ];
    }
    return [
        'id',
        'name'
    ];
}
like image 309
Alex Pavlov Avatar asked May 08 '17 05:05

Alex Pavlov


2 Answers

What about using the $select property?

$query = User::find()->select(['id','email','count']);
$activeData = new ActiveDataProvider([
    'query' => $query,
    'pagination' => [
        'pageSize' => 10,
     ],
]);

Or even better, create an ActiveQuery class for them:

class UserQuery extends ActiveQuery
{
     public function statistics()
     {
        return $this->select(['id','email','count']);
     }

     /* add as many filtering functions as you need here */
}

Then override the find() method in the User class to use it:

public static function find()
{
    return new \app\models\UserQuery(get_called_class());
}

Then do:

$activeData = new ActiveDataProvider([
    'query' => User::find()->statistics(),
    'pagination' => [
        'pageSize' => 10,
     ],
]);

Note: In default implementation of Yii2 RESTful API you can also select the required fields within url by doing: GET /users?fields=id,email,count

like image 95
Salem Ouerdani Avatar answered Oct 23 '22 05:10

Salem Ouerdani


Simply get all the models using getModels() method, set scenario for all of them in the loop and then return data provider. Your example will change into following code:

$query = User::find();
$activeData = new ActiveDataProvider([
    'query' => $query,
    'pagination' => [
        'pageSize' => 10,
    ],
]);
foreach($activeData->getModels() as $model) {
    $model->scenario = 'statistics';
}
return $activeData;
like image 2
nostop Avatar answered Oct 23 '22 04:10

nostop