james james - 20 days ago 5
reST (reStructuredText) Question

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.

Answer

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;
}