yiisoft / yii2

Yii 2: The Fast, Secure and Professional PHP Framework
http://www.yiiframework.com
BSD 3-Clause "New" or "Revised" License
14.24k stars 6.9k forks source link

UniqueValidator: option to exclude self #14943

Open vercotux opened 7 years ago

vercotux commented 7 years ago

This is a feature request to add a boolean excludeSelf (or filterSelf) option to UniqueValidator.

Such an option is particularly useful when updating an existing record which already has the unique attribute set. Right now UniqueValidator will add an error if we update the unique value to the same value, which is not right imo. Even though the unique attribute is marked as dirty, if it is identical to the original one, it should pass validation or even skip the check entirely.

It seems to be a rather common issue:

cebe commented 7 years ago

the unique validator takes the case into account when the model is updated, so the record that is currently updated does not count as a duplicate record on update. This is also verified by a unit test:

https://github.com/yiisoft/yii2/blob/52d0d004acf96c07c3f63d4535220c4993d695c6/tests/framework/validators/UniqueValidatorTest.php#L98-L101

Can you provide some code to reproduce the problem? The links to stackoverflow does not contain useful info as far as I see.

https://stackoverflow.com/questions/40485357/skip-yii2-unique-validation-on-update-action-if-new-value-equals-to-prev-value

according to the answer the problem was due to a typo.

https://stackoverflow.com/questions/44469776/yii2-on-update-action-for-unique-attribute

unable to reproduce.

https://stackoverflow.com/questions/35629904/set-unique-rule-to-a-field-on-update-action-on-yii2-rest

unable to reproduce. The solution adds a problem that updating the field does not check for uniqueness!?

https://stackoverflow.com/questions/35695940/ajax-validation-unique-on-update

The problem here is a typo in targetClass, SmCategory vs. Smcategory.

https://stackoverflow.com/questions/33052744/how-to-validate-data-to-unique-when-the-data-is-changed-on-update

These seem to be generally confused about what they want.

yii-bot commented 7 years ago

Thanks for posting in our issue tracker. In order to properly assist you, we need additional information:

Thanks!

This is an automated comment, triggered by adding the label status:need more info.

vercotux commented 7 years ago

I was able to reproduce the issue. This seems to happen in a very specific situation where you have multiple unrelated unique attributes in the same model and at least 2 are marked as dirty (but identical to their original/old values!). And I think one of them has to be the primary key.

For example:

$model = SomeModel::find()->one();
$model->markAttributeDirty('id');
$model->markAttributeDirty('another_unique_column');
$model->validate(); // will report 'another_unique_column' as taken.