我采取了扩大形式助手类别的做法,在形式领域添加错误的类别名称,并显示外地标签上的错误信息。
<?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);
}
}
You then pass in the $errors
array into the label and field helper methods:
<?php echo
Form::label( username , Username , NULL, $errors),
Form::input( username , $user->username, NULL, $errors);
?>
在科加纳论坛提出了这一想法,但我竭力寻找最初的线索。 不管怎么说,我发现这一办法对我来说是最好的。
[edit] View an example of this approach in action here: http://kohana3.badsyntax.co/contact (submit the form)