Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
PHP
branch: master

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.
README.textile
UniqueBoolValueValidator.php

README.textile

UniqueBoolValueValidator

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:

  1. if $object→$attribute != $single_single_bool_value, then NO validation error is flagged (and no DB check is performed – no need to).
  2. 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

  1. Concurrency issues are not handled at all. No locking is done, no isolation levels, nothing.
  2. 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…
    );
Something went wrong with that request. Please try again.