raiym
raiym

Reputation: 1499

Hide password in Yii2 in model when user request information

https://github.com/yiisoft/yii2/blob/master/docs/guide/structure-models.md#fields-

I've read this article but can't understand how it works. I wrote it in my code, but with no luck. In model class fields like this:

public function fields() {
    $fields = parent::fields();

    // remove fields that contain sensitive information
    unset($fields['password']);

    return $fields;
}

For example I want return information about one user:

$account = Account::findOne($id);
return Json::encode(['error' => 0, 'message' => '', 'data' => $account]); 

And when I want return a bunch of users:

$accounts = Account::find()->where(['companyId' => $companyId])->orderBy('username')->asArray()->all();
return Json::encode(['error' => 0, 'message' => 'Users in company', 'data' => $accounts]);

So how to hide fields?

Upvotes: 0

Views: 2102

Answers (2)

Kazux Kazux
Kazux Kazux

Reputation: 151

Your code is correct and it will hide the password field

If u want another way u can select the fields you want to show like this:

$accounts = Account::find()
    ->select(['field1','field2'])
    ->where(['companyId' => $companyId])->orderBy('username')
    ->asArray()
    ->all();
return Json::encode(['error' => 0, 'message' => 'Users in company', 'data' => $accounts]);

Upvotes: 2

tnchalise
tnchalise

Reputation: 1583

Its Pretty Simple:

Just try $account->fields();

Upvotes: 0

Related Questions