【问题标题】:How to add default value in cakephp select option?如何在 cakephp 选择选项中添加默认值?
【发布时间】:2015-11-11 21:58:00
【问题描述】:

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

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 作为默认值。

【问题讨论】:

    标签: cakephp cakephp-2.0


    【解决方案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 数组。您刚刚将一个数组传递给您的inputoptions 属性。

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

    $options = array(1, 2, 3, 4, 5);
    echo $this->Form->input('field', array(
        'options' => $options,
        'default' => $options[1]; // '2' in the defined array
    ));
    

    【讨论】:

      【解决方案2】:

      Read Book

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

      【讨论】:

      • 如果我的输入类似于 echo $this->Form->input('book_category_id'); ,如果我想要第二个数据是默认的,那么你的代码可以吗?
      • 您是否从数据库中获取数据,并在表单中填写选项?
      【解决方案3】:

      你可以试试这个

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

      这是食谱中的link

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

      【讨论】:

      • 这不设置默认值。 value 将覆盖 $this->request->data 中设置的任何值,这不是一回事。
      猜你喜欢
      • 2019-02-09
      • 1970-01-01
      • 2016-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-06
      • 1970-01-01
      相关资源
      最近更新 更多