Bin will be removed on June 1, 2014 in favor of http://gist.github.com. Please save all your pastes before then. So long, and thanks for all the fish!×
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
/**
 * An example about how to use a custom validation rule to
 * get a conditional "is unique", i.e., if a model field
 * "flag" is false, "thefield" can be duplicates.  But if
 * the record has a flag value true, no more duplicates are
 * allowed.
 * Nice to use when you can do several tries of saving data,
 * saving the success and fail to get the real data saved.
 */
class MyModel extends AppModel {
    var $validate   = array(
        'somefield' => array('rule'=> array('condUnique', array('thefield', 'flagfield')), 'message'=> 'Duplicates not allowed')
        ));
 
/**
 * Conditional unique.
 * @param  mixed   $value  the value of the model's field (not used)
 * @param  array   $params an array with the fieldname and the flagfield to use in comparation
 * @return boolean true if the corresponding field value already exists and the flag is false, or if not exists and flag is true.
 */
    function condUnique($value, $params) {
 
        $field  = $params[0];
        $flag   = $params[1];
        $this->data = $this->create($this->data);
 
        if( !$this->data[$this->alias][$flag] ) return true;
        else {
 
            $fieldVal   = $this->data[$this->alias][$field];
 
            $existingFieldsCount    = $this->find('count', array(
                  'conditions'=> array(
                      'and'=> array(
                          $this->alias.'.'.$flag=> true
                        , $this->alias.'.'.$field=> $fieldVal
                    )
                )
                , 'recursive'=> -1
            ));
            return $existingFieldsCount == 0;
        }
    }