B
B
Bohdan_Vasilchuk2015-10-08 19:37:19
Yii
Bohdan_Vasilchuk, 2015-10-08 19:37:19

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'],
        ];
    }
}

Validation rules: all fields are required, e-mail must be entered in the "Login" field, and a unique value must be entered in the "Login" field that does not exist in the "login" column of the "users" table.
The essence of the problem:
If the rules() method is left as it is above, and from the form fields, fill in only one Login field with a valid e-mail, but invalid by uniqueness, then submit the form, then the "Name" and "Password" fields will be highlighted in red and next to them will be displayed messages about the invalidity of the data. At the same time, the value in the "Login" field is displayed as valid (although it is not unique).
If absolutely all validation rules are removed in the rules() method, except for the uniqueness of the login, and the form is sent with the same data (only the correct, but not unique e-mail), then this rule will work and a message will be displayed stating that such a login is already exist.
Bottom line:
The unique rule only fires when it is the only rule in the rules() method
Question:
Why is this happening and what needs to be done to make the uniqueness check work along with other rules?

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
A
Alexander, 2015-10-09
@Bohdan_Vasilchuk

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]);

2. In the create / update controller, give validation errors
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
    Yii::$app->response->format = Response::FORMAT_JSON;
    return ActiveForm::validate($model);
}

In the original example, if you enter the correct username and password and a valid but not unique login and submit the form, it will return with a non-unique login validation error. Everything works and works;)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question