Toma Tomov Toma Tomov -4 years ago 135
PHP Question

Sidestep the default username and email when validate it with ajax unique Yii2

How can i sidestep current username and password of the user when updating his information? For example - when i try to update only the name it shows me that email is already taken and vice versa. That way i can not update only the or only the email, only both of them.
My actionUpdate:

public function actionUpdate()
$model = new UpdateForm();
$id = \Yii::$app->user->identity->id;
$user = $this->findModel($id);

//default values
$model->username = $user->username;
$model->email = $user->email;

if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);

if (isset($_POST['UpdateForm']))
$model->attributes = $_POST['UpdateForm'];


$user->username = $model->username;
$user->email = $model->email;
$user->password = md5($model->password);


$this->redirect(['view', 'id' => $user->id]);
return $this->render('update', [
'model' => $model,

My UpdateForm rules:

public function rules()
return [
[['email', 'password', 'username'], 'required'],
[['email', 'password', 'username'], 'string', 'max' => 50],
[['image'], 'string', 'max' => 255],
[['username', 'password', 'email'], 'trim'],
['email', 'email'],
[[ 'email', 'username'], 'unique'],

Thank you in advance!

Answer Source

you should use both for unique


// a1 and a2 need to be unique together, and they both will receive error message
[['a1', 'a2'], 'unique', 'targetAttribute' => ['a1', 'a2']]

in your case

[[ 'email', 'username'], 'unique', 'targetAttribute' => ['email', 'username']],

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download