Cakephp $this->request->data返回选择字段的id,而不是在选择字段中需要和显示的值


Cakephp $this->request->data returns id of select field instead of value which is needed and shown in the select field

我有一个像这样的CakePHP控制器:

$this->loadModel('Project');
$list2 = $this->Project->find( 'list', array(
    'fields'     => array('Project.project'),
    'conditions'    => array('Project.user_id' => $userId)
));
$this->set($list2, 'list2');
$this->loadModel('Distance');
if(!empty($this->request->data)){    
    $this->Distance->create();
    if ($this->Distance->save($this->request->data)) {
        $this->Session->setFlash('Saved.');
        //  $this->redirect(array('action' => 'index'));
    } else {
        $this->Session->setFlash('FAILED');
    }
}else{
    //  $this->Session->setFlash('test');
}

和这样的视图:

echo $this->Form->input('Distance.project', array('options' => $list2, 'label' => false, 'empty' => '(choose one)'  ;

但是我将项目的id而不是项目名称插入到数据库中。我在处理字段时从来没有遇到过这样的问题——只是处理一个数据列表。

知道为什么会这样吗?

这很正常…$list2它是和数组…选项的值是该数组的索引。

如果您只想插入项目名称,则需要将$list2更改为$list2['project_name']。您需要删除或替换$list2的索引。

LE:举个例子。

 $list2 = $this->Project->find( 'list', array(
                    'fields'     => array('Project.project'),
                     'conditions'    => array('Project.user_id' => $userId)
                 )
         );

这是因为$list2自动创建了一个ID => project的列表;当你使用它作为表单的输入时,它会自动创建下拉框来反映这个。这通常是最佳实践,链接到ID而不是描述,因为ID不会经常更改。下面的代码可以让你得到你想要的:

 $list2 = $this->Project->find( 'list', array(
                    'fields'     => array('Project.project','Project.project'),
                     'conditions'    => array('Project.user_id' => $userId)
                 )
         );