JeevaRekha
JeevaRekha

Reputation: 413

Ignore validation on soft deleted models

I have user table. I created a form with 3 fields:

The first two fields are unique. Model rules for those fields look like this:

[['Username', 'phonenumber'], 'required'],
[['Username', 'phonenumber'], 'unique'],

I use soft deletion, so when record is deleted, it actually stays in database but status value will change to 0.

The problem is, if I add a record with existing username it shows an error message like "already added". I need to ignore validation if username have a status with value 0.

Upvotes: 4

Views: 835

Answers (2)

arogachev
arogachev

Reputation: 33548

Use filter property of UniqueValidator

public function rules()
{
    return [
        ...

        ['username', 'unique', 'filter' => ['<>', 'status', 0]];

        ...
    ];
}

It's better to declare constant instead of 0 (something like const STATUS_DELETED = 0) and user it as self::STATUS_DELETED inside of User class. Also you can use != instead of <>.

The last recommendation will be to use username instead of Username to follow convention of naming database table columns.

Read more about ways of declaring filter in official docs.

The ways of setting filter condition as array is described here.

Upvotes: 5

user5212481
user5212481

Reputation: 51

You can use your own function to decide the given username already exists in active status or not. Use this function in "when" property of your unique validation rule.

Have a look :

public function rules()
{
    $check = function($model) { 
    $existActiveUser = User::model()->findByAttributes(array("username"=>$model->username,"status"=>1));
    if($existActiveUser)
        return true;
    else
        return false;
};
return [
    ['Username', 'phonenumber'], 'required'],
    [['Username','phonenumber'],'unique','when'=>$check],
}

Upvotes: -1

Related Questions