我是CakePHP的初学者,我使用的是3.5版本。我真的很困惑。我的问题是我想从两个不同的模型中合并两个表单。在我的例子中,我想在一个表单中合并客户端事务添加表单和服务详细信息添加表单。以下是我的代码:
add.ctp(我在服务详细信息添加表单中合并了添加客户端事务表单)
<div class="serviceDetail form large-9 medium-8 columns content">
<?= $this->Form->create($clientTransaction) ?>
<fieldset>
<legend><?= __('Add Client Transaction') ?></legend>
<?php
echo $this->Form->control($serviceDetail->client_transaction->client->id, ['options' => $clients]);
echo $this->Form->control($serviceDetail->client_transaction->client->transaction_date, ['timeFormat' => 12, 'disabled' => false]);
echo $this->Form->control($serviceDetail->client_transaction->client->status, ['type' => 'hidden', 'value' => 0]);
?>
</fieldset>
<?= $this->Form->create($serviceDetail) ?>
<fieldset>
<legend><?= __('Add Service Detail') ?></legend>
<?php
echo $this->Form->control('service_id', ['options' => $service, 'empty' => true]);
echo $this->Form->control('user_id', ['options' => $users, 'empty' => true, 'label'=> ['text' => 'Barber']]);
echo $this->Form->control('client_transaction_id', ['options' => $clientTransaction, 'empty' => true]);
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
在我的service_detail控制器
中public function add()
{
$this->paginate = [
'contain' => ['Service', 'Users', 'ClientTransaction']
];
$clientTransaction = $this->ServiceDetail->ClientTransaction->newEntity();
$serviceDetail = $this->ServiceDetail->newEntity();
if ($this->request->is('post')) {
$clientTransaction = $this->ServiceDetail->ClientTransaction->patchEntity($clientTransaction, $this->request->getData());
$serviceDetail = $this->ServiceDetail->patchEntity($serviceDetail, $this->request->getData());
if ($this->ServiceDetail->ClientTransaction->save($clientTransaction) && $this->ServiceDetail->save($serviceDetail)) {
$this->Flash->success(__('The transaction has been added.'));
return $this->redirect(['action' => 'add']);
}
$this->Flash->error(__('Please, try again.'));
}
$service = $this->ServiceDetail->Service->find('list', ['limit' => 200]);
$users = $this->ServiceDetail->Users->find('list',['limit' => 200, 'valueField' => 'first_name'])->where(['position' => 2]);
$clientTransaction = $this->ServiceDetail->ClientTransaction->find('list', ['limit' => 200]);
$clients = $this->ServiceDetail->ClientTransaction->Clients->find('list', ['limit' => 200]);
$serviceDetail = $this->paginate($this->ServiceDetail);
$this->set(compact('serviceDetail', 'service', 'users', 'clientTransaction'));
}
答案 0 :(得分:0)
做这样的事情:
$serviceDetail = $this->ServiceDetail->newEntity(
$this->request->getData(), [
'associated' => ['ClientTransaction']
]
);
https://book.cakephp.org/3.0/en/orm/saving-data.html#converting-request-data-into-entities
对于您的页面,请遵循以下模式: https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-inputs-for-associated-data