I am building a simple application in CakePHP in which users can register with data saved in the users table in my database. They also have a profile associated with the user, and I am trying to accomplish this by utilizing the $hasOne and $belongsTo association. The user hasOne profile and the profile belongs to the user.
I have created a profiles table with id, and user_id, and other fields for the profile. The user_id references the id of the profile. However, when I am trying to edit the profile information in the view, I cannot update information. I get an error that says it is trying to duplicate the 'id' which corresponds to the User id in the User table. I am writing my profile_edit function in the UsersController.php, here is the code:
public function profile($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException('Invalid user');
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->save($this->request->data)) {
$this->request->data['Profile']['user_id'] = $this->User->id;
$this->User->Profile->save($this->request->data);
$this->Session->setFlash('Your profile has been updated');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('The profile could not be saved. Please, try again.');
}
} else {
$this->request->data = $this->User->read();
}
}
My Profile.php Model file:
<?php
class Profile extends AppModel {
public $name = 'Profile';
public $belongsTo = 'User';
}
?>
And my views file:
<div class="profiles form">
<?php echo $this->Form->create('User');?>
<fieldset>
<legend>Edit Profile</legend>
<?php
echo $this->Form->input('Profile.regulator_number');
echo $this->Form->input('Profile.website');
echo $this->Form->input('Profile.minimum_account');
?>
</fieldset>
<?php echo $this->Form->end('Submit');?>
</div>
<div class="actions">
<h3>Actions</h3>
<ul>
<li><?php echo $this->Html->link('List Users', array('action' => 'index'));?></li>
</ul>
</div>
I want to be able to update the profiles information for each user, whether or not they have filled anything out yet or not. NOTE: if a new user registers and does not have any Profile information yet, the submit works fine. Only update is messed up. Do I maybe need to add the user_id into the profile table as soon as a user registers, as of now a newly registered user may have information in the users table but not the profiles table.
Thanks in advance for the help.