I have a one-to-one relation between an Account and a User table, I'm trying to do all the pre-processing in the beforeSave
of the account model, but it seems like i can only change the values of $this->data['Account'][...]
and not $this->data['User'][...]
, why is so?
function beforeSave() {
// Check if this is a create or update action
if (empty($this->data['Account']['uid'])) {
$this->data['Account']['uid'] = uniqid();
$this->data['Account']['date_registrati开发者_运维问答on'] = date('Y-m-d');
$this->data['Account']['state'] = 1;
// this won't work
$this->data['User']['password'] = Security::hash($this->data['User']['password'], null, true);
}
return true;
}
Another question is what's the best way to check if the user is updating or creating the model in the beforeSave event, check for empty($this->data['Account']['id']))
?
Thanks.
It turned out it's not possible in CakePHP 1.3: http://cakephp.lighthouseapp.com/projects/42648/tickets/671-cant-modify-related-models-data-in-beforesave-when-using-saveall
I moved the code to the User controller, however this time the problem is i can't directly access $this->Account->name, although i can access $this->Account->id, why is that? i had to do the workareound below:
function beforeSave() {
if (empty($this->date['User']['id'])){
$this->data['User']['password'] = Security::hash($this->data['User']['password'], null, true);
// Username is inherited from the account name
// TODO: the field needs to be removed, depending whether the Auth component will play nicely
$account_name = $this->Account->read('name',$this->Account->id);
$this->data['User']['username'] = $account_name['Account']['name'];
}
return true;
}
精彩评论