What I'm trying to reach is to register a User
and a Firm
at once. So I would need to insert into 3 tables: users
, firms
, and firms_users
. CakePHP should do this automatically, because I've set the $hasAndBelongsToMany
associtation in the models. But during the registration, only the users
table gets written. Am I missing something?
registration form
<div class="users form">
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('Add User'); ?></legend>
<?php
echo $this->Form->input('User.email', array('type' => 'email')); //standard HTML5 email validation
echo $this->Form->input('User.password');
echo $this->Form->input('Firm.0.name');
echo $this->Form->input('Firm.0.zipcode');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
</div>
the relevant part of User
model
public $hasAndBelongsToMany = array(
'Firm' => array(
'className' => 'Firm',
'joinTable' => 'firms_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'firm_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
),
and the relevant part of Firm
model
class Firm extends AppModel {
public $hasAndBelongsToMany = array('User'=>array('className'=>'User'));
finally the UsersController / show_reg_form action
public function show_reg_form(){
if ($this->request->is('post')) {
$this->loadModel('Firm');
$this->User->create();
$this->Firm->create();
if ($this->User->saveAll($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
return $this->redirect(array('action' => 'loggedin','loggedin'));
}
$this->Session->setFlash(
__('The user could not be saved. Please, try again.')
);
}
}