james james - 1 year ago 207
reST (reStructuredText) Question

Change one attribute value Yii2 REST API

I have created a REST API in Yii2 using

. The default implementation of
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

Answer Source

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 [
        '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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download