Reputation: 413
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
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
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