I guess you are not using yii\rest\ActiveController but yii\rest\Controller. ActiveController defines actions you can extend like in your example. If you don’t want to use ActiveController just copy it’s actions() method and work from that point.
Edit —
Sorry, my bad, you are using proper controller but you are using prepareDataProvider wrong. It’s not in ViewAction (which is for single resource only). It’s for IndexAction.
Hi!
Thanks for your answer, just found the notification in my spam folder.
So, yes, I’m using the proper ActiveController as you mentionned. What I was trying to accomplish is to change the dataProvider for the viewAction, so for a single resource. Still haven’t found a way to accomplish that though.
Ok… I might be trying to do this the wrong way then.
Real-life example. I want to return a post only if it was published in the category my connected user is part of? How can I modify the query the api uses for the viewAction to add that constraint to the query?
Edit: I could create my own viewAction class and update the actions() array to load mine. I guess that makes sense!
Yes, you can create your own. Also you can use findModel:
$actions['view']['findModel'] = static function ($id, Action $action) {
$modelClass = $action->modelClass;
$model = $modelClass::findOne(/* what you need */);
if ($model === null) {
throw new NotFoundHttpException("Object not found: $id");
}
return $model;
};
I’m not new to Yii, I used it with Craft CMS for a while, but I’m new starting an application with it myself. It’s in these time you can appreciate the work that was put into the full app on top of Yii!