大家好,我正在使用cakephp创建表单。在这里,我使用了一个选择下拉列表。此下拉列表从数据库中填充。我有两个表,分支和员工。 Branch表中的PrimaryContactID是外键。这个选择下拉列表中填充了Employee表中的EmployeeID(截至目前)。但是,我需要,下拉列表应该显示名称,保存时我应该保存ID。
这就是我写的:
controller:
public function add()
{
$branch = $this->Branch->newEntity();
if ($this->request->is('post')) {
$branch = $this->Branch->patchEntity($branch, $this->request->data);
if ($this->Branch->save($branch)) {
$this->Flash->success(__('The branch has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The branch could not be saved. Please, try again.'));
}
}
$employee = $this->Branch->Employee->find ( 'list', [
'limit' => 200
] );
$this->set(compact('branch', 'employee'));
$this->set('_serialize', ['branch']);
}
BranchTable.php:
class BranchTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->table('branch');
$this->displayField('BranchID');
$this->primaryKey('BranchID');
$this->addBehavior('Timestamp');
$this->belongsTo('Employee', [
'foreignKey' => 'EmployeeID',
'joinType' => 'INNER'
]);
}
}
add.ctp:
<div class="branch form large-9 medium-8 columns content">
<?= $this->Form->create($branch) ?>
<fieldset>
<legend><?= __('Add Branch') ?></legend>
<?php
echo $this->Form->input('BranchName');
echo $this->Form->input('BranchCode');
echo $this->Form->input('Address');
echo $this->Form->input('Telephone');
echo $this->Form->input('PrimaryContactID', ['options' => $employee]);
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>
截至目前,下拉列表中填充了EmployeeID的值。我需要的是,我需要同时拥有EmployeeID和EmployeeName。当我点击下拉列表时,我应该看到EmployeeName,在保存时我应该保存ID。
怎么做?我应该做的所有改变是什么?
答案 0 :(得分:1)
调用列表时,您可以配置用于键和的字段 分别使用keyField和valueField选项的值:
$employee = $this->Branch->Employee->find('list', [
'keyField' => 'EmployeeID',
'valueField' => 'EmployeeName',
//'limit' => 200
]);
详细了解如何检索数据&amp;结果:
<强> http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html 强>
答案 1 :(得分:0)
//write your query like this
$employee = $this->Branch->Employee->find('list')->select(['EmployeeID','EmployeeName']));