Monday, April 22, 2013

Checking Consistency Before Saving

I have a table of students with foreign keys of province_id and a country_id. And the table of provinces has a foreign key of country_id just like the students table.

I want to make sure that a student doesn't get saved with a province that doesn't match the country. I put this into my Student model and it works, but I want to know if I'm following best practices.

Can anyone suggest a better way to do this?

public function beforeValidate(array $options = array()) {
if ($this->data['Student']['province_id']) {
$p = new Province();
$this->set('province', $p->findById($this->data['Student']['province_id']));
if ($this->data['Student']['province']['Province']['country_id'] != $this->data['Student']['country_id']) {
$this->invalidate('province_id', 'Invalid province for the selected country');
return false;
}
}
return true;
}

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP
 
---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

No comments: