如何在CakePHP中显示从数据库中获取的数据的数组到下拉列表? [英] How to display an array ,of fetched data from database, to dropdown list in CakePHP?

查看:44
本文介绍了如何在CakePHP中显示从数据库中获取的数据的数组到下拉列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我在将数组(从数据库中获取)分配给下拉列表时遇到了问题。这是代码

Hi everyone I am facing problem assigning array(fetched from database) to dropdown list. Here is the Code

控制器代码

$skill_rows = $this->Skill->find("all");
$this->set(compact("skill_rows"));

CTP代码

$skills = $skill_rows;
echo $this->Form->select("Seeker.skills",$skills,array("empty"=>"Select"));

数据库

id   skill
1    PHP
2    CakePHP

我希望

推荐答案

使用 $ this- > Skill-> find( list); 返回可以在下拉菜单中使用的主键显示字段值的数组。您可能需要指定技能作为 displayField 才能正常工作。

Use $this->Skill->find("list"); to return an array of primary key-display field values that can be used in your dropdown. You might need to specify skill as the displayField for this to work correctly.

CakePHP 2

在CakePHP 2中, displayField 是一个模型的属性:-

In CakePHP 2 the displayField is an attribute of the model:-

class Skill extends AppModel {

    public $displayField = 'skill';

}

或者,您可以定义要返回的列执行 find()时的列表:-

Alternatively you can define the columns you want to be returned in the list when you perform your find():-

$this->Skill->find('all', [
    'fields' => [
        'Skill.id',
        'Skill.skill'
    ]
]);

CakePHP 3

在CakePHP 3中,您可以在模型中定义 displayField :-

In CakePHP 3 you can define the displayField in the model:-

class SkillsTable extends Table
{

    public function initialize(array $config)
    {
        $this->displayField('skill');
    }
}

如果要在<$ c上执行此操作在CakePHP 3中的$ c> find()查询中,您需要定义 keyField valueField :-

If you want to do this on the find() query in CakePHP 3 you need to define the keyField and valueField:-

$this->Skill->find('list', [
    'keyField' => 'id',
    'valueField' => 'skill'
]);

这篇关于如何在CakePHP中显示从数据库中获取的数据的数组到下拉列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆