I have created a REST API in Yii2 using ActiveController
. The default implementation of actionIndex
return all the models.
What i want to do is to change the value of one attribute before sending response.
for example i have image uploaded with just its name stored in database.
Before sending a response i want to embed the base URL with image name.
Do i need to override the whole index method or i can manipulate the single attribute in action
method?
Asked
Active
Viewed 1,204 times
0

Mushahid Hussain
- 4,052
- 11
- 43
- 62
-
overriding the action is what will be the solution in your case as you want to modify the data also – Kandarp Patel Jun 23 '16 at 05:41
-
modify the value in action before sending response – Yasin Patel Jun 23 '16 at 05:43
2 Answers
3
I think the easiest way to do this is override the fields()
method in your model. Lets say you have your ActiveController configured for a model called YourFile
. If you add the following function to the YourFile
model the full url can be added for every model in the response:
public function fields() {
return [
'id',
'name' => function() {
return Url::base(true) . $this->name;
}
]
}
If you add it like this, it does mean that every code calling toArray()
on your model will get this result. If you only want it to happen for the ActiveController
you might want to extend the YourFile
model and include the fields()
method only there, so you can configure the ActiveController
with the extended version.

Jap Mul
- 17,398
- 5
- 55
- 66
1
We can also change the display name of certain fields:
class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface {
/** * API safe fields */
public function fields() {
return [
'id',
'email_address' => 'email',
'first_name',
'last_name',
'full_name' => function($model) {
return $model->getFullName();
},
'updated_at',
'created_at'
];
}
}
see full tutorial here: http://p2code.com/post/configuring-activecontroller-display-fields-yii-2-21

Tien Vu
- 11
- 1
- 3