Yii 1.1: uniqueboolvaluevalidator

Validator that makes sure that only a single record with $attribute_name = $single_bool_value exists in the DB
2 followers

General

This validator class validates that for the given $object, only a single record with $attribute_name = $single_bool_value exists in the DB. Where is it useful? This is best answered in an example: suppose you have polls system and only one 'poll' can be 'published on frontpage'. This property (published on front page) is represented in the DB in the form of some boolean column. Using this validator you can make sure that only one such poll is always "promoted to front page". This validator will not alter the existing poll's 'promoted' field - that's another business logic not handled here.

Techy description

Algorithmicly speaking, this means that:

  • if $object->$attribute != $single_single_bool_value, then NO validation error is flagged (and no DB check is performed - no need to).
  • if $object->$attribute == $single_single_bool_value, then a check against the DB is made to verify that no other record exists with this value ($single_bool_value), and flag an error according to the findings.

IMPORTANT LIMITATIONS

  • Concurrency issues are not handled at all. No locking is done, no isolation levels, nothing.
  • This validator accepts and supports $object of type CActiveRecord ONLY. This is natural since the validator checks stuff in the DB so this is relevant for "DB related CModels", meaning CActiveRecord objects.

Requirements

Tested on Yii v1.1.10. Should probably work on older versions but didn't try.

Usage

  • Extract the contents of the download package. There should be a single class file and a README file. The readme should be the same as here.
  • Put the class file under /protected/components.
  • In your relevant AR model, update its rules() method to the following:
return array(
  // other validation rules appear here...
  array(attribute_name, 'UniqueBoolValueValidator'),
  // other validation rules appear here...
);

The default value allowed only once in the DB is true. If you wish it to be false, do as follows:

return array(
  // other validation rules appear here...
  array(attribute_name, 'UniqueBoolValueValidator', 'single_bool_value' => false),
  // other validation rules appear here...
);

Change log

July 1st, 2012: v1.0 - updated 'category' when calling Yii::t() to something more general. Please update your usage according to your preferences.

Resources

Be the first person to leave a comment

Please to leave your comment.

Create extension