I am learning cakephp by myself. I tried to create a user controller with a changepassword function. It works, but I am not sure if this is the best way, and I could not goo
I see that you validate and manipulate data in the controller. Doing this in a model is generally a better practice. I implemented similar functionality just a few days ago. My change_password() method looks somewhat like this:
# app/controllers/users_controller.php
function change_password() {
if (!empty($this->data)) {
if ($this->User->save($this->data)) {
$this->Session->setFlash('Password has been changed.');
// call $this->redirect() here
} else {
$this->Session->setFlash('Password could not be changed.');
}
} else {
$this->data = $this->User->findById($this->Auth->user('id'));
}
}
And here's a stripped down version of the view used with that method:
# app/views/users/change_password.ctp
echo $this->Form->create('User');
echo $this->Form->input('id');
echo $this->Form->input('current_password');
echo $this->Form->input('password1');
echo $this->Form->input('password2');
echo $this->Form->end('Submit');
The code that does something interesting is in the model. I added the fields from the form to the validate property and wrote custom validation methods. This allows me to use password1 and password2 fields in any other place in the application, for example, on the registration form.
# app/models/user.php
var $validate = array(
'current_password' => array(
'rule' => 'checkCurrentPassword',
'message' => '...'
),
'password1' => array(
'rule' => 'checkPasswordStrength',
'message' => '...',
),
'password2' => array(
'rule' => 'passwordsMatch',
'message' => '...',
)
);
Finally, in the beforeSave() callback of the model I set password to the hash of password1 to prepare the data to be stored it in the database.