S
S
Sergey Beloventsev2016-08-12 15:34:53
Yii
Sergey Beloventsev, 2016-08-12 15:34:53

How not to save a field marked as required and unique in the model when editing?

there is a User model
here is the rule

public function rules()
        {
            return [
                ['username', 'required'],
                //['username', 'match', 'pattern' => '#^(p{L}|p{Zs}|p{N}|,|-|_ | |)+$#i'],
                ['username', 'unique', 'targetClass' => self::className(), 'message' => 'This username has already been taken.'],
                ['username', 'string', 'min' => 2, 'max' => 255],
    
                ['email', 'required'],
                ['email', 'email'],
                ['email', 'unique', 'targetClass' => self::className(), 'message' => 'This email address has already been taken.'],
                ['email', 'string', 'max' => 255],
    
                ['status', 'integer'],
                ['status', 'default', 'value' => self::STATUS_ACTIVE],
                ['status', 'in', 'range' => array_keys(self::getStatusesArray())],
            ];
        }

there is a need to allow the user to change only the nickname, the question is, how in this case to disable email validation because the model is not validated due to the fact that either the email is not unique or it needs to be filled in?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Fedorov, 2016-08-12
@Sergalas

use scripts. You can read more about them here

D
Dmitry Kim, 2016-08-15
@kimono

class UserModel extends ActiveRecord {
  const SCENARIO_UPDATE = 'update';

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

class UserController extends Controller {
  public function actionUpdate(){
    $model = new UserModel();
    $model->scenario = UserModel::SCENARIO_UPDATE;
    // ...
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question