Marc
Marc

Reputation: 493

Cakephp update password

I am trying to edit one of my members password (i have been allowed by the user).

Now for this function i have the following action:

        if (!$this->User->exists($id)) {
        throw new NotFoundException(__('Invalid USer'));
    }
    if ($this->request->is('post') || $this->request->is('put')) {
        if ($this->User->save($this->request->data)) {
            $this->Session->setFlash(__('The User has been saved'));
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The User could not be saved. Please, try again.'));
        }
    } else {
    }
}

However when i try to save i get the following error:

2013-10-21 11:53:53 Error: [PDOException] SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'MarcEmp' for key 'username'

So it tries to insert a new entry.

Does anyone know what i am doing wrong?

Upvotes: 0

Views: 472

Answers (1)

Oldskool
Oldskool

Reputation: 34837

You are forgetting to set the current id to update, so Cake will try to create a new record by default. Try adding:

$this->User->id = $id;

Just before the save operation. So your entire function should look like:

/**
 * Edit an existing user.
 *
 * @param int $id The user id to edit.
 */
public function edit($id) {
    if (!$this->User->exists($id)) {
        throw new NotFoundException(__('Invalid User'));
    }
    if ($this->request->is('post') || $this->request->is('put')) {
        $this->User->id = $id; // <-- Add it here
        if ($this->User->save($this->request->data)) {
            $this->Session->setFlash(__('The User has been saved'));
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The User could not be saved. Please, try again.'));
        }
    }
}

Upvotes: 3

Related Questions