1
<?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 --')
?>

Is there a faster way to add a default option in a select? Thank you.

4

2 回答 2

0

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

如果您想要不完全支持任何自定义行为,您可以使用自己的代码扩展 Form::select()。我知道 Kohana 强烈建议扩展其核心类,但我还没有玩过 Kohana3。在 Kohana2 中,您会按照此处所示的方式进行操作。根据 Kohana3 的本教程,你会做类似的事情,但将你的新文件放在 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
         */
    }
}
于 2010-09-13T19:05:09.273 回答
0

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

参考Arr::unshift()

<?php echo Form::select('marcas', Arr::unshift($marcas, '', '--Selecione--') , false);?>
于 2011-07-04T13:33:55.577 回答