Mushahid Hussain
Mushahid Hussain

Reputation: 4055

Restrict certain attributes from updating Yii2

I am making a REST API using Yii2. In Put request method during update i want to restrict user to not able to update his/her email address. Is there a way that we can achieve this? Right now when user send put request with changed email address the email address gets changed.

Upvotes: 0

Views: 249

Answers (1)

uldis
uldis

Reputation: 362

Use model scenarios See Model Scenarios

Model

namespace app\models;

use yii\db\ActiveRecord;

class User extends ActiveRecord
{
    const SCENARIO_API = 'API';
    const SCENARIO_OTHER = 'OTHER';

    public function scenarios()
    {
        return [
            self::SCENARIO_API => ['username', 'password'],
            self::SCENARIO_OTHER => ['username', 'email', 'password'],
        ];
    }
}

Controller:

namespace app\controllers;
use yii\rest\ActiveController;
use app\models\User;

class UserController extends ActiveController
{
    public $modelClass = 'app\models\User';
    public $createScenario = User::SCENARIO_API;
}

Upvotes: 1

Related Questions