Reputation: 671
I'm working on a user model that needs to generate a key if the user's field is empty. If the user already has a key in the database, we wouldn't need to generate a new one. Where and what would be the best way to do this?
One:
User without a key stored in the database:
Model should generate a new key and save it to the user.
Two:
User with a key already in the database:
Model shouldn't change anything, except what the save was already going to modify.
Upvotes: 0
Views: 964
Reputation: 2014
Presuming key and id are either interchangeable or easily bound, validation and Cake magic should cover this for you. If the data you are evaluating might contain an id for existing records (such as User.id, for example), Cake automatically checks data for the presence of an id and generates an INSERT statement if there is no id in the data, or an UPDATE statement if there is. You can then use validation in the model to prevent an update of data that has an id.
Upvotes: 0
Reputation: 128
There's a beforeSave method that get's invoked before data is saved to the database. You could do something like this:
public function beforeSave() {
if (isset($this->data['User']['id'])) {
$user = $this->find->('first', array(
'conditions'=>array('User.id'=>$this->data['User']['id'])
));
if (!$user['User']['key']) {
$this->data['User']['key'] = $this->_generateKey();
}
}
return TRUE;
}
protected function _generateKey() {
// generate key here
return $key;
}
Good luck
Upvotes: 3