[英]Codeigniter Grocery Crud update field?
$crud->set_rules('user_password', 'Password', 'trim|required|matches[konfirmpass]');
$crud->set_rules('konfirmpass', 'Konfirmasi Password', 'trim|required');
$crud->callback_edit_field('user_password',array($this,'_user_edit'));
$crud->callback_add_field('user_password',array($this,'_user_edit'));
回调函数:
function _user_edit(){
return '<input type="password" name="user_password"/> Confirmation password* : <input type="password" name="konfirmpass"/>';
}
我的问题是,如果只有“密码”不是空白,如何更新?
我已经安装了CI 2.0.3和GC 1.1.4进行测试,因为您的代码一目了然。 事实证明,这是和你的代码一起工作的。 我使用GC修改了examples
控制器中开箱即用的employees_management
方法。 在数据库中添加了user_password列,并将代码添加到控制器中。
代码既可以确保密码字段匹配,也可以在提交时不为空。
"The Password field is required"
"The Password field does not match the konfirmpass field."
结果"The Password field does not match the konfirmpass field."
也许如果这不适合你,你应该发布你的整个方法而不仅仅是规则和回调,这样我们就可以看出是否还有其他问题。
编辑
要编辑该字段,只有在编辑了密码后才需要添加
$crud->callback_before_update( array( $this,'update_password' ) );
function update_password( $post ) {
if( empty( $post['user_password'] ) ) {
unset($post['user_password'], $post['konfirmpass']);
}
return $post;
}
但是,这可能意味着您需要删除空密码的验证,具体取决于回调运行的顺序(如果它们在表单验证运行之前或之后)。 如果它们在表单验证之前运行,则还需要运行对callback_before_insert()
的调用,并在两个回调中添加验证规则。 显然,插入将需要required
规则,而更新则不会。
编辑2,编辑澄清1
经过调查,验证在回调之前运行,因此您无法在回调函数中设置验证规则。 要实现这一点,您需要使用一个名为getState()
的函数,它允许您根据CRUD执行的操作添加逻辑。
在这种情况下,我们只想在添加行时使密码字段成为required
,而在更新时则不需要。
因此,除了上面的回调update_password()
,您还需要将表单验证规则包装在状态检查中。
if( $crud->getState() == 'insert_validation' ) {
$crud->set_rules('user_password', 'Password', 'trim|required|matches[konfirmpass]');
$crud->set_rules('konfirmpass', 'Konfirmasi Password', 'trim|required');
}
如果CRUD正在插入,这将添加验证选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.