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?
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.