这就是我进行模型验证的方式,我觉得这是最直接、最优雅的。
首先,我在 Rules() 方法中设置规则:
<?php defined('SYSPATH') or die('No direct access allowed.');
class Model_Brand extends ORM {
public function rules()
{
return array(
'name' => array(
array('not_empty'),
array('min_length', array(':value', 3)),
array('max_length', array(':value', 20)),
)
'sku' => array(
array('not_empty'),
array('min_length', array(':value', 3)),
array('max_length', array(':value', 6)),
)
);
);
}
这就是我管理编辑操作的方式:
public function action_edit()
{
$brand = ORM::factory('brand', $this->request->param('id'));
if (!$brand->loaded())
{
throw new Kohana_Exception('Brand not found.');
}
$this->template->title = __('Edit Brand');
$this->template->content = View::factory('brands/edit')
->set('brand', $brand)
->bind('errors', $errors);
if ($this->request->method() === Request::POST)
{
try
{
$brand->values($this->request->post());
$brand->save();
// Success! You probably want to set a session message here.
$this->request->redirect($this->request->uri());
}
catch(ORM_Validation_Exception $e)
{
// Fail!
$errors = $e->errors('brand');
}
}
}
在我看来:
<?php if ($errors) {?>
<!-- display errors here -->
<?php } ?>
<?php echo Form::open()?>
<fieldset>
<div class="field">
<?php echo
Form::label('name', __('Name')),
Form::input('name', $brand->name)
?>
</div>
<?php echo Form::submit('save', 'Save')); ?>
</fieldset>
<?php echo Form::close()?>
正如您在视图中看到的,我没有进行任何条件检查来查看表单字段中显示的内容,因为它是由模型中的数据管理的,而模型由控制器管理。
希望这对您有所帮助,如果您需要进一步说明,请询问。