首页 文章

Codeigniter Grocery Crud更新字段?

提问于
浏览
1
$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"/>';   
}

我的问题是,如果只有“密码”不是空白,如何更新?

1 回答

  • 4

    我已经安装了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." 中的结果不匹配

    也许如果这对您不起作用,您应该发布整个方法而不仅仅是规则和回调,以便我们可以看到是否还有其他问题 .

    Working

    Edit

    要编辑该字段,只有在编辑了密码后才需要添加

    $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 规则,更新不会 .

    Edit 2, Clarification of Edit 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,这将添加验证选项 .

相关问题