I have a posts table linked with a students table in a hasMany relation.
And the students table is linked with a subjects table in a hasAndBelongsToMany relation:
posts hasMany students
students HABTM subjects
There is a form submitted from PostController. The form has several fields (multiple checkbox) for students to choose their subjects respectively:
<?php echo $this->Form->input('Student.0.Subject'); ?>
<?php echo $this->Form->input('Student.1.Subject'); ?>
<?php echo $this->Form->input('Student.2.Subject'); ?>
I need to make sure every student chooses at least one subject, but Cake validation does not work like it should. I tried tweaking this approach to my needs, but it doesn't seem to work. Not sure where I'm doing it wrong?
function beforeValidate($options = array()) {
$test = Router::getParams();
if ($test['pass'][0] == '3') {
//check the field only if it's in step 3
if (empty($this->data['Student'][0]['Subject'])) {
$this->invalidate('non_existent_field'); // fake validation error
$this->invalidate('Student.0.Subject', 'Please select at least one subject');
}
return true;
}
}
fyi $this->request->data['Student'][0]['Subject']
does return empty '' string..
EDIT:
$this->invalidate doesn't seem to work. I debug it and it returns null
.