Kohana框架:添加默认选项
问题描述:
<?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 --')
?>
有没有更快的方式来添加默认选项的选择? 谢谢。Kohana框架:添加默认选项
答
你的方式看起来非常快速和优雅,利用现有的框架功能和一些智能数据来利用它。
如果您想要完全不支持任何自定义行为,您可以使用自己的代码扩展Form :: select()。我知道Kohana强烈建议扩展其核心课程,但我还没有与Kohana3玩过。在Kohana2中,你会这么做as seen here。根据this tutorial Kohana3的说法,你可以这样做,但将新文件放在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
*/
}
}
答
不过要小心,如果您使用的是例如作为数据库值数组键查找字段。 Array_unshift将重新编排您的内容,所以你可能更喜欢Arr::unshift($marcas, '', '--Selecione--');
。另一优点是返回数组,这样你就可以在函数调用PARAMS中,而不是作为一个单独的线路上使用
<?php echo Form::select('marcas', Arr::unshift($marcas, '', '--Selecione--') , false);?>
有什么在'Form :: select()'中选择'Selecione - '参数的原因?你应该使用数组键而不是值:'Form :: select('marca',$ marcas,0)' – biakaveron 2010-09-14 05:50:06