【问题标题】:Cakephp $this->request->data returns id of select field instead of value which is needed and shown in the select fieldCakephp $this->request->data 返回选择字段的 id 而不是需要并显示在选择字段中的值
【发布时间】:2013-02-25 17:13:12
【问题描述】:

我有一个像这样的 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 而不是项目名称插入到数据库中。 我在使用这些字段时从来没有遇到过这样的问题 - 只是使用数据列表。

知道为什么会这样吗?

【问题讨论】:

    标签: php list cakephp view controller


    【解决方案1】:

    这很正常... $list2 it's 和数组... 选项的值是该数组的索引。

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

    LE:以 iexiak 为例。他还为您更改代码。

    【讨论】:

    • 谢谢,如果我有足够的声誉,我会投票给你们两个的答案!!! :)
    【解决方案2】:
     $list2 = $this->Project->find( 'list', array(
    
                        'fields'     => array('Project.project'),
                         'conditions'    => array('Project.user_id' => $userId)
                     )
    
             );
    

    这是因为 $list2 会自动创建 ID => 项目的列表;当您将其用作表单的输入时,它会自动创建下拉列表以反映这一点。这通常是最佳实践,链接到 ID 而不是描述,因为 ID 不会经常更改。不过,以下内容应该可以为您提供您想要的:

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

    【讨论】:

      猜你喜欢
      • 2012-02-20
      • 2015-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多