简体   繁体   中英

Override default rest action in Yii2

I created rest api in yii2 for the users. I can access list of users like this "api/web/v1/users" but the problem is that it is giving the data of all the columns including password, I saw in yii2 documentation that it is internally calling "user/index" method, is there any way to override the index method like this?

 class UserController extends ActiveController {
 public $modelClass = 'common\models\User';
        public function actionIndex(){
        //return selected columns here of the user table
        }
}

It still gives the list of all users with all columns that I don't want. Please help.

In your case, you must use fields() method and override this method. As Yii defines fields() :

By overriding [[yii\\base\\Model::fields()|fields()]] and/or [[yii\\base\\Model::extraFields()|extraFields()]], you may specify what data, called fields, in the resource can be put into its array representation.You can override fields() to add, remove, rename or redefine fields

For example:

public function fields()
{
    return [    
        'id','name','username'
    ];
}

Above method, tells yii that only show id , name , username fields. So, Password will never be sent to client.

In cases that you want only remove one or more specific fields, you can do like below:

public function fields()
{
    $fields=parent::fields();
    unset($fields['password']);
    return $fields;
}

While the accepted answer does work and is an important method to know for basic control of what fields are shared via rest and general "object exporting" functions like Json::encode(), I feel it is important to also understand how to completely override an action like the OP references.

I've answered this question here: https://stackoverflow.com/a/50744982/3337682 , and I feel it would be helpful, added information for the OP.

Hope this helps someone!

~ Cheers :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM