0
votes

Table structure

 id, chart_id, date, rate
 Datapoint belongsTo Chart

I'm trying to make a unique index validation rule on chart_id, date. I have tried validating with the plugin, MultiColumnUniqueness, but it always returns true.

EDIT: This wasn't the problem. This is valid for checking multi-column uniqueness. See below. Model validation with MultiColumnUniqueness:

 public $actsAs = array('MultiColumnUniqueness.MultiColumnUniqueness' => array(
        'fields' => array('chart_id', 'date'),
        'errMsg' => "This date for this chart has already been used."
));

Is there a way to validate multi-column unique indices with dates in CakePHP?

EDIT: My data array is the following structure:

 array(
'Datapoint' => array(
    (int) 0 => array(
        'id' => '1055',
        'date' => array(
            'month' => '12',
            'year' => '2012',
            'day' => '01'
        ),
        'active' => '1',
        'num' => '15',
        'days' => '897',
        'chart_id' => '4'
    ),
    (int) 1 => array(
        'id' => '1054',
        'date' => array(
            'month' => '12',
            'year' => '2012',
            'day' => '01'
        ),
        'active' => '1',
        'num' => '4',
        'days' => '768',
        'chart_id' => '4'
    )
 );

SOLVED: WalkingRed's solution worked as well as the plugin I was using but that wasn't the problem. I was attempting to validate before saving a saveAssociated with a $this->Chart->validates(). Turns out you need to validate multiple rows by a different method if you are just validating:

  if ($this->Chart->saveAssociated($this->request->data, array('validate' => 'only'))) {
        // validates
     } else{
        $errors = $this->Chart->invalidFields(); //validation error
     }
1

1 Answers

0
votes

Have you added something similar in model?

public $validate = array(
    'chart_id' => array(
        'unique_first_last' => array(
            'rule'    => array('checkMultiColumnUnique', array('chart_id', 'date'), false)
            'message' => 'Chart and date must be unique.'
        )
    ),
;)


public function checkMultiColumnUnique($ignoredData, $fields, $or = true) {
        return $this->isUnique($fields, $or);
}