在 cakephp 中动态绑定 select 下拉菜单

Dynamically binding the select dropdown in cakephp

大家好,我正在使用 cakephp 创建一个表单。在这里,我使用了 select 下拉菜单。这个下拉列表是从数据库中填充的。我有两个 tables,Branch 和 Employee。 Branch table 中的 PrimaryContactID 是外键。此 select 下拉列表中填充了员工 table 的员工 ID(截至目前)。但是,我需要像这样,下拉菜单应该显示名称,并且在保存时我应该保存 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。

怎么做?我应该做哪些改变?

When calling list you can configure the fields used for the key and value with the keyField and valueField options respectively:

$employee = $this->Branch->Employee->find('list', [ 
    'keyField' => 'EmployeeID',
    'valueField' => 'EmployeeName',
    //'limit' => 200
]);

详细了解如何检索数据和结果:

http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html

//write your query like this

$employee = $this->Branch->Employee->find('list')->select(['EmployeeID','EmployeeName']));