views:

72

answers:

2

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.

A: 

You could put it in app model, but my suggestion would just be to add it to the model directly by placing the rule with it's $validate property.

Check out the built in isUnique rule.

Jason McCreary
'isUnique' validates only one field for a single column. I need the validation rule for two columns that compose the composite unique key.
bancer
I see. Sorry. Then yes, if this is something in multiple models, I would built a custom validation rule and put it in app_model.php.
Jason McCreary
+1  A: 

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.

Nik
Thanks! That is exactly what I wanted. The only outpoint is that it produces 2 identical queries when 2 fields are validated.
bancer