如何在cakephp select选项中添加默认值?

时间:2015-11-11 07:26:20

标签: cakephp cakephp-2.0

我想在输入字段中添加默认选择选项 例如,如果我对这段代码

echo $this->Form->input('field', array(
    'options' => array(1, 2, 3, 4, 5),
    'empty' => '(choose one)'
));

我想更改此代码,如

echo $this->Form->input('field', array(
    'options' => array(1, 2, 3, 4, 5),
    'default' => options[1];  // it's not correct, I just want to add 2 as a default value.
));

这里我想添加选项2作为默认值。

3 个答案:

答案 0 :(得分:1)

Read Book

echo $this->Form->input('field', array(
    'options' => array(1, 2, 3, 4, 5),
    'default' => '2'
));

答案 1 :(得分:1)

你可以试试这个

$options = array(1, 2, 3, 4, 5);
$attributes = array('value' => 2, 'empty' => false);
echo $this->Form->select('field', $options,$attributes);

这是来自cookbook的link

如果您从数据库中获取结果然后填入select选项,那么只需将值$this->request->data['Model']['field'] = 'value';放入控制器中,它将成为选择下拉列表中的默认值

答案 2 :(得分:1)

问题在于您编写的PHP。您试图引用您的default并不存在的内容并且不是正确的PHP变量: -

echo $this->Form->input('field', array(
    'options' => array(1, 2, 3, 4, 5),
    'default' => options[1];  // it's not correct, I just want to add 2 as a default value.
));

options[1]不是有效的PHP变量,因为您错过了$符号,并且$options数组尚未定义。您刚刚将数组传递给options的{​​{1}}属性。

您需要先定义input数组,然后将其传递给$options,如下所示: -

$this->Form->input()
相关问题