我已經採取了擴展窗體幫助程序類的方法,以在窗體字段上添加「錯誤」類名稱,並在字段標籤中顯示錯誤消息。
<?php defined('SYSPATH') or die('No direct script access.');
class Form extends Kohana_Form {
private static function attributes($name, & $attributes = NULL, $errors = NULL)
{
// Set the id attribute
if (!isset($attributes['id']))
{
$attributes['id'] = $name;
}
if ($errors !== NULL)
{
// Merge in external validation errors.
$errors = array_merge($errors, (isset($errors['_external']) ? $errors['_external'] : array()));
// Set the error classname
if (isset($errors[$name]))
{
$attributes['class'] = trim((string) @$attributes['class'].' error-field');
}
}
}
public static function input($name, $value = NULL, array $attributes = NULL, array $errors = NULL)
{
static::attributes($name, $attributes, $errors);
return parent::input($name, $value, $attributes);
}
public static function select($name, array $options = NULL, $selected = NULL, array $attributes = NULL, array $errors = NULL)
{
static::attributes($name, $attributes, $errors);
return parent::select($name, $options, $selected, $attributes);
}
public static function password($name, $value = NULL, array $attributes = NULL, array $errors = NULL)
{
static::attributes($name, $attributes, $errors);
return parent::password($name, $value, $attributes);
}
public static function textarea($name, $body = '', array $attributes = NULL, $double_encode = TRUE, array $errors = NULL)
{
static::attributes($name, $attributes, $errors);
return parent::textarea($name, $body, $attributes, $double_encode);
}
public static function file($name, array $attributes = NULL, array $errors = NULL)
{
static::attributes($name, $attributes, $errors);
return parent::file($name, $attributes);
}
public static function label($input, $text = NULL, array $attributes = NULL, array $errors = NULL, $view = 'messages/label_error')
{
if ($errors !== NULL)
{
// Merge in external validation errors.
$errors = array_merge($errors, (isset($errors['_external']) ? $errors['_external'] : array()));
// Use the label_error view to append an error message to the label
if (isset($errors[$input]))
{
$text .= View::factory($view)->bind('error', $errors[$input]);
}
}
return parent::label($input, $text, $attributes);
}
}
然後通過$errors
數組的標籤和字段的輔助方法中:
<?php echo
Form::label('username', 'Username', NULL, $errors),
Form::input('username', $user->username, NULL, $errors);
?>
這個想法被建議在Kohana的論壇,但我一直在努力尋找原來的線程。無論如何,我發現這種方法最適合我。
[編輯]查看這種方法的一個例子在這裏的行動:http://kohana3.badsyntax.co/contact(提交表單)
謝謝,這是我一直在尋找的功能。好的解決方案,應該內置。這也是一個很棒的小演示網站。那不是可以下載的嗎? – Coder1 2012-01-15 16:19:17
歡迎在這裏看看:https://github.com/badsyntax/kohana3-examples(這基本上是演示網站後面的代碼),但我不建議嘗試下載並使其運行爲事情已經破裂。代碼是相當古老的,所以把所有東西都用一小撮鹽..在很多情況下,我會以不同的方式做現在的事情。 – badsyntax 2012-01-15 16:34:58
如果我可以爲後期綁定,很好地使用通過引用,@ @屬性和一些寫得很好的github上的參考代碼。非常感謝!如果您可以更新代碼庫以使其成爲最新版本,那將是甜蜜的。 – aleemb 2012-05-02 20:24:43