Dubby
Dubby

Reputation: 2402

How to return fields depending on RESTful action?

I am building a RESTful application in Yii2 and I have overwritten the fields() method in the model (extending ActiveRecord) but I want to define which fields to be returned depending on whether the request was view or list.

It's easy to check in the controller which RESTful action is in use by dumping the $actions variable in the actions method. How can I do something similar in the model? I tried checking the scenario but of course it's default.

Upvotes: 1

Views: 548

Answers (1)

Tony
Tony

Reputation: 5867

There is several ways, i will describe two of them.

1) Very easy and simple: call \Yii::$app->controller->action->uniqueId in your model's fields() method to determine which action is used.

2) According to your comment, ActionController define its actions in actions method, which returns array of actions and their configurations, e.g. for view action:

'view' => [
    'class' => 'yii\rest\ViewAction',
    'modelClass' => $this->modelClass,
    'checkAccess' => [$this, 'checkAccess'],
],

so in your child controller you can override parent implementation and set your action classes for each action, like this:

public function actions()
{
    $myActions = [
        'view' => [
            'class' => 'app\actions\MyViewAction',
        ]
    ];
    return ArrayHelper::merge(parent::actions(), $myActions);
}

Here app\actions\MyViewAction is your custom action class which you can inherit from yii\rest\Action and override run() method.

public function run($id)
{
    $model = $this->findModel($id);
    if ($this->checkAccess) {
        call_user_func($this->checkAccess, $this->id, $model);
    }
    $model->scenario = 'view';
    return $model;
}

and then check scenario in your model and do appropriate actions. Hope this will help

Upvotes: 2

Related Questions