Triggering model validation with CakePHP
I'm creating a form so users can change their passwords. This form is in
my settings controller, but I'm saving the data to my users table.
I have the following form
settings/index.ctp
echo $this->Form->create('settings');
echo $this->Form->input('current_password');
echo $this->Form->input('password');
echo $this->Form->input('repass', array('type'=>'password',
'label'=>'Re-Enter Password'));
echo $this->Form->end(__('Submit'));
Here's my Setting model
function equalToField($array, $field) {
print_r($array);
return strcmp($this->data[$this->alias][key($array)],
$this->data[$this->alias][$field]) == 0;
}
public function beforeSave() {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] =
AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
public $validate = array(
'password' => array(
'required' => array(
'rule' => array('minLength', '8'),
'message' => 'A password with a minimum length of 8 characters
is required'
)
),
'repass' => array(
'required' => array(
'rule' => array('equalToField', 'password'),
'message' => 'Passwords do not match'
)
)
);
And the code in my SettingsController to save it
$password =
Security::hash($this->request->data['settings']['current_password'], NULL,
true);
$this->loadmodel('User');
$options = array('conditions' => array('User.' . $this->User->primaryKey
=> AuthComponent::user('id')));
$user = $this->User->find('first', $options);
if($user['User']['password'] == $password){ //current password match
$this->User->id = AuthComponent::user('id');
$this->User->saveField('password',Security::hash($this->request->data['settings']['password'],
NULL, true));
}
else{
$this->Session->setFlash('Current password is incorrect');
}
What am I doing incorrectly that the validation isn't triggering? I'd
prefer to keep this in my SettingsController if possible. Also, before
anyone mentions it I plan on making the current password match into one of
the validation criteria...just as soon as I get it working.
No comments:
Post a Comment