【问题标题】:Kohana Framework: add default optionKohana 框架:添加默认选项
【发布时间】:2010-09-13 18:34:06
【问题描述】:
<?php
// My controller.
$marcas = ORM::Factory('marca')->
find_all()->
as_array('nome', 'nome');
array_unshift($marcas, '-- Selecione --');
?>

<?php
// My view.
echo Form::select('marca', $marcas, '-- Selecione --')
?>

有没有更快的方法在选择中添加默认选项? 谢谢。

【问题讨论】:

  • Form::select() 中的 '-- Selecione --' 参数是否有任何理由?您应该使用数组键而不是值:Form::select('marca', $marcas, 0)

标签: php orm frameworks rad kohana-3


【解决方案1】:

您的方式看起来非常快速和优雅,使用现有的框架功能和一些智能数据来利用它。

如果您想要不完全支持任何自定义行为,您可以使用自己的代码扩展 Form::select()。我知道 Kohana 强烈建议扩展其核心类,但我还没有玩过 Kohana3。在 Kohana2 中,你会这样做 as seen here。根据 Kohana3 的 this tutorial,您可以类似地执行此操作,但将新文件放在 application/classes 文件夹中。

大胆猜测这是如何工作的:在 application/classes 中创建 form.php 并输入:

class Form extends Form_Core {

    public static function select() {
        /**
         * Add the code from http://dev.kohanaframework.org/projects/kohana3-core/repository/revisions/master/entry/classes/kohana/form.php#L252
         * and change it slightly to also include a default value when writing out
         * the form, or even better via another optional function parameter
         */
    }
}

【讨论】:

    【解决方案2】:

    如果您使用数组键作为数据库值,例如作为查找字段,请小心。 Array_unshift 将重新编号您的元素,因此您可能更喜欢Arr::unshift($marcas, '', '--Selecione--');。另一个优点是返回数组,因此您可以在函数调用参数中使用而不是作为单独的行

    参考Arr::unshift()

    <?php echo Form::select('marcas', Arr::unshift($marcas, '', '--Selecione--') , false);?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-09
      • 1970-01-01
      • 1970-01-01
      • 2022-07-26
      • 2010-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多