The problem: I want to create a company and its associated user using single form for company create
I have baked the scaffold and using CakePHP convention.
my association setup:-
CompaniesTable class
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('companies');
$this->setDisplayField('name');
$this->setPrimaryKey('id');
$this->hasMany('Users', [
'foreignKey' => 'company_id'
]);
}
UsersTable
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('users');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsTo('Companies', [
'foreignKey' => 'company_id',
'joinType' => 'INNER'
]);
$this->belongsToMany('Roles', [
'foreignKey' => 'user_id',
'targetForeignKey' => 'role_id',
'joinTable' => 'roles_users'
]);
}
I have used following code in my add.ctp to generate fields for user
code of add method in the controller
public function add()
{
$this->viewBuilder()->setLayout(false);
$company = $this->Companies->newEntity();
if ($this->request->is(‘post’)) {
$company = $this->Companies->patchEntity($company, $this->request->getData());
if ($this->Companies->save($company)) {
$this->Flash->success(__('The company has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The company could not be saved. Please, try again.'));
}
$this->set(compact('company'));
$this->set('_serialize', ['company']);
}
my request data
[
‘name’ => ‘x’,
‘print_name’ => ‘x’,
‘address_line1’ => ‘x’,
‘address_line2’ => ‘x’,
‘city’ => ‘x’,
‘state’ => ‘x’,
‘country’ => ‘x’,
‘pincode’ => ‘x’,
‘current_financial_year’ => ‘x’,
‘organization_start_date’ => [
‘year’ => ‘2021’,
‘month’ => ‘03’,
‘day’ => ‘04’
],
‘currency_name’ => ‘x’,
‘currency_symbol’ => ‘x’,
‘currency_subname’ => ‘x’,
‘symbol_of_partition’ => ‘x’,
‘symbol_to_print’ => ‘xx’,
‘multi_currency_management’ => ‘0’,
‘has_pan’ => ‘0’,
‘has_gst’ => ‘0’,
‘has_tds’ => ‘0’,
‘has_tcs’ => ‘0’,
‘pan_number’ => ‘’,
‘gst_number’ => ‘’,
‘tds_number’ => ‘’,
‘tcs_number’ => ‘’,
‘pan_date’ => [
‘year’ => ‘2017’,
‘month’ => ‘12’,
‘day’ => ‘02’
],
‘gst_date’ => [
‘year’ => ‘2017’,
‘month’ => ‘12’,
‘day’ => ‘02’
],
‘tds_date’ => [
‘year’ => ‘2017’,
‘month’ => ‘12’,
‘day’ => ‘02’
],
‘tcs_date’ => [
‘year’ => ‘2017’,
‘month’ => ‘12’,
‘day’ => ‘02’
],
‘users’ => [
(int) 0 => [
‘user_name’ => ‘james’,
‘password’ => ‘password’
]
]
]
Thanks in advance for your help