Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2: Can I use scenarios to specify different set of model fields for different actions?

I can see in the Yii2 model page (http://www.yiiframework.com/doc-2.0/yii-base-model.html), in the "fields" section that you can set "different lists of fields based on some context information. For example, depending on $scenario or the privilege of the current application user, you may return different sets of visible fields or filter out some fields."

But, scenarios documentation (http://www.yiiframework.com/doc-2.0/guide-structure-models.html#scenarios) says scenarios is for creating different context for model attributes validation.

I'm using Yii2 Restful API, where I have to use default actions (actionIndex, actionView, ...) to get data from model and show as API results. I know I can override those methods (http://www.yiiframework.com/doc-2.0/guide-rest-controllers.html#extending-active-controller), but how can I say in those methods to use different set of fields (depending on different scenarios) ?

What I need is to output field1, field2, field3 for actionIndex (items list), but I want to output field1, field2, field3, field4 for actionView (item list).

like image 333
FlamingMoe Avatar asked Oct 20 '22 02:10

FlamingMoe


1 Answers

You do it in your model.

Default REST implementation in Yii2 will only include attributes that are returned by the fields() method. By default, that method returns all attributes. Therefore, you define it like so:

class MyModel extends ActiveRecord
{
    //...
    public function fields()
    {
        switch ($this->scenario) {
            case 'my_scenario_1':
                return ['field1', 'field2'];
            case 'my_scenario_2':
                return ['field3', 'field4'];
        }
    }
}

Also, you have the scenarios() method at your disposal, which returns all active attributes for a given scenario.

Don't forget to set the models' scenario in your controller.

like image 58
Beowulfenator Avatar answered Oct 22 '22 21:10

Beowulfenator