在 CakePHP 中将名字和姓氏显示为 select 选项

Show prename and lastname as select option in CakePHP

我想用 CakePHP 显示一个表单,用户可以在其中 select 一个员工。 Cake 将输入字段显示为 "select",这很好。不幸的是,select 输入字段仅显示员工的 id 而不是 prenamelastname

型号:

提醒:

worker_id (reference to Worker model)

工人:

id
prename
lastname

这是PHP部分:

echo $this->Form->create('Reminder', 
    array('action' => 'add',
        'inputDefaults' => array(
            'label' => false,
            'div' => false
        )
    )
); 

echo $this->Form->input('worker_id', array('empty' => 'Choose an employee'));
echo $this->Form->button('Save', array('type' => 'submit', 'class' => 'btn btn-green')); 

我没有找到显示 class Workerprenamelastname 的方法,但将 id 作为选项值保留在 select字段。

如何做到这一点?

您需要如下创建 $your_listing

$your_listing = array('2'=>'John Fleming','3'=>'Justin Bond');

并在您的表单助手中使用此数组,如下所示

echo $this->Form->input('worker_id', array('empty' => 'Choose an employee','options'=>$your_listing)); 

所以在上面的例子中,select 框变成了

<select name="worker_id">
  <option id="">Choose an employee</option>
  <option id="2">John Fleming</option>
  <option id="3">Justin Bond</option>
  </select>

您可以使用数组来指定 select 输入的选项。

$options =  array(
    'Value 1' => 'Label 1',
    'Value 2' => 'Label 2'
)
echo $this->Form->input('worker_id', $options,  array('empty' => 'Choose an employee'));

在你的情况下你的标签应该是 Worker.id => Worker.prename + Worker.lastname