Problem: When editing an entry SQL is making an INSERT instead of an UPDATE.
I have two SQL tables : users and users_detail.
users(id,role,name,password) &
users_detail(id,adress,city,user_id)
Foreign key users_detail.user_id is linked to users.id.
I have a form in my cakephp app to edit users_detail, if a user wants to edit his adress for example. Here is my controller :
public function admin_edit_dashboard($id = null){
if (!$this->User->exists($id)) {
throw new NotFoundException('Invalid user details');
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->UserDetail->save($this->request->data, true, ['id', 'address', 'city'])) {
$this->Session->setFlash('The user has been saved');
return $this->redirect(array('action' => 'dashboard'));
} else {
$this->Session->setFlash('The user could not be saved. Please, try again.');
}
} else {
//$this->request->data = $this->User->read(null, $id);
$user = $this->User->UserDetail->find('first', array(
'conditions' => array(
'UserDetail.user_id' => $id
)
));
$this->request->data = $user;
}
$this->set(compact('user'));
}
And my form :
<?php echo $this->Form->create('UserDetail');?>
<?php echo $this->Form->input('address', array('class' => 'form-control')); ?>
<br />
<?php echo $this->Form->input('city', array('class' => 'form-control')); ?>
<br />
<?php echo $this->Form->button('Submit', array('class' => 'btn btn-primary')); ?>
<?php echo $this->Form->end(); ?>
But when I'm validate the form to edit details I have an error :
Error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY'
Because the SQL query isn't an UPDATE but an INSERT. I don't know why.
SQL Query: INSERT INTO
cake.user_details(adress_ex,city_ex) VALUES ('roses street', 'London')
Thank you!
EDIT : It works, thanks for your help! Good code added.
admin_edit_dashboard? - skywalker