Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation rule for a composite unique index (non-primary)

I am sure I am not the first who has composite unique keys in tables and who wants to validate them. I do not want to invent the bicycle so I ask here first. I have several tables that have 'id' columns as primary keys and two other columns as unique composite keys. It would be nice to have a validation rule to check that the submitted entry is unique and display a validation error if it is not. In Cakephp it could be done by a custom validation rule. I am pretty sure somebody has created such method already.

Ideally it would be a method in app_model.php that could be used by different models.

like image 499
bancer Avatar asked Aug 10 '10 01:08

bancer


1 Answers

I am using that function:

function checkUnique($data, $fields) {
    if (!is_array($fields)) {
            $fields = array($fields);
        }
        foreach($fields as $key) {
            $tmp[$key] = $this->data[$this->name][$key];
        }
    if (isset($this->data[$this->name][$this->primaryKey]) && $this->data[$this->name][$this->primaryKey] > 0) {
            $tmp[$this->primaryKey." !="] = $this->data[$this->name][$this->primaryKey];
        }
    //return false;
        return $this->isUnique($tmp, false); 
    }

basically the usage is:

'field1' => array(
                'checkUnique' => array(
                    'rule' => array('checkUnique', array('field1', 'field2')),
                    'message' => 'This field need to be non-empty and the row need to be unique'
                ),
            ),
'field2' => array(
                'checkUnique' => array(
                    'rule' => array('checkUnique', array('field1', 'field2')),
                    'message' => 'This field need to be non-empty and the row need to be unique'
                ),
            ),

So basically this will show the warning under each of the fields saying that it's not unique.

I am using this a lot and it's working properly.

like image 55
Nik Chankov Avatar answered Nov 08 '22 03:11

Nik Chankov