Answer the question
In order to leave comments, you need to log in
How to set up the Unique validation rule in Yii2 so that it works correctly?
I have a form with three fields. The model is shown below.
<?php
namespace app\models;
use Yii;
use yii\db\ActiveRecord;
class Add extends ActiveRecord
{
const PERMISSIONS_PRIVATE = 10;
const PERMISSIONS_PUBLIC = 20;
public $name;
public $login;
public $password;
private $connection;
public function __construct()
{
$this->connection = Yii::$app->db;
}
public static function tableName(){
return 'users';
}
public function rules()
{
return [
[['name','login','password'], 'required'],
[['login'], 'email'],
[['login'], 'unique'],
];
}
}
Answer the question
In order to leave comments, you need to log in
The unique rule doesn't work with client-side validation, but the doc forgot to mention it.
In this case, the easiest way is to use ajax validation of the login field:
1. In the view, enable validation for the field
$form->field($model, 'login', ['enableAjaxValidation' => true]);
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question