php-Kohana ORM和验证,有问题
作者:互联网
试图通过适用于Kohana 3.2的ORM进行验证.
目前,我有我的模特:
<?php defined('SYSPATH') or die('No direct access allowed.');
class Model_Brand extends ORM {
protected $_has_many = array('models' => array());
protected $_rules = array(
'name' => array(
'not_empty' => NULL,
'min_length' => array(3),
'max_length' => array(20),
),
'sku' => array(
'not_empty' => NULL,
'min_length' => array(3),
'max_length' => array(6),
),
);
}
这是我的控制器:
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Brand extends Controller_Layout {
public function action_view()
{
$brands = ORM::factory('brand')->find_all();
$this->template->title = __('Brands');
$this->template->content = View::factory('brands/view' );
$this->template->content->set('brands', $brands);
}
public function action_edit()
{
if($_POST)
{
try
{
$brand = ORM::factory('brand', $this->request->param('id'));
$brand->values($_POST);
if($brand->check())
{
$brand->update();
$brand->save();
//go to brand/views
}
}
catch (ORM_Validation_Exception $e)
{
//pass errors to brand/edit
}
}
else
{
$brand = ORM::factory('brand', $this->request->param('id'));
$this->template->title = __('Edit Brand');
$this->template->content = View::factory('brands/edit' );
$this->template->content->set('brand', $brand);
}
}
}
我什至还没有到错误部分.我遇到的问题是它可以对任何输入进行验证,而不能使用模型中的规则.同样,如果有人可以告诉我如何设计这样的更新操作,将大有帮助.谢谢.
解决方法:
这就是我进行模型验证的方式,我觉得这是最简单明了的.
首先,我在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()?>
正如您在视图中看到的那样,我没有进行任何条件检查以查看在表单字段中显示什么,因为这是由模型中的数据管理的,而模型是由控制器管理的.
希望对您有所帮助,请问是否需要进一步说明.
标签:kohana,validation,orm,php 来源: https://codeday.me/bug/20191101/1985861.html