mardi 3 mars 2015

Save data into 2 tables cakephp 3

I am very new to Cakephp 3. I try to do saveAll function in Cakephp 3, but unsuccessful.


I have 2 tables : Merchants and Users


Relationship between this 2 tables as below:


Users hasMany Merchants, Merchants belongsTo Users


I want the create a merchant's registration form that will insert the data to both tables.


Can someone help me how to insert data into 2 different tables from 1 form using Cakephp 3?


My code as below:



<?= $this->Form->create($merchant); ?>
<fieldset>
<legend><?= __('Add Merchant') ?></legend>
<?php
echo $this->Form->input('User.id');
echo $this->Form->input('User.username');
echo $this->Form->input('User.password');
echo $this->Form->input('merchant_type_id', ['options' => $merchantTypes]);
echo $this->Form->input('name');
echo $this->Form->input('identity_number');
echo $this->Form->input('phone_number');
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>


Controller:



public function registration()
{
$merchant = $this->Merchants->newEntity();
if ($this->request->is('post')) {
$merchant = $this->Merchants->patchEntity($merchant, $this->request->data, [
'associated' => ['Users']
]);
if ($this->Merchants->saveAll($merchant)) {
$this->Flash->success('The merchant has been saved.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The merchant could not be saved. Please, try again.');
}
}
$users = $this->Merchants->Users->find('list', ['limit' => 200]);
$merchantTypes = $this->Merchants->MerchantTypes->find('list', ['limit' => 200]);
$this->set(compact('merchant', 'users', 'merchantTypes'));
}


Your helps is very appreciated. Thanks.


Aucun commentaire:

Enregistrer un commentaire