简体   繁体   English

CodeIgniter 3-通过配置文件进行的可调用表单验证不起作用

[英]CodeIgniter 3 - Callable Form Validation by Config file not working

I am unable to get the callable form validation feature of CodeIgniter 3 to work when the validation rules are placed in a separate config file . 验证规则放在单独的配置文件中时,无法使用CodeIgniter 3的可调用表单验证功能来工作。

I am getting the following error message: 我收到以下错误消息:

A PHP Error was encountered 遇到PHP错误
Severity: Notice 严重程度:注意
Message: Undefined property: CI_Config::$form_validation_callback_library 消息:未定义的属性:CI_Config :: $ form_validation_callback_library

The config file with the form validation rules are as follows (config/fvalidation.php): 带有表单验证规则的配置文件如下(config / fvalidation.php):

$config['client_details'] = array(
    array(
            'field' => 'client_abn',
            'label' => 'Client ABN',
            'rules' => array('trim', 'required', array('abn_callable', array($this->form_validation_callback_library, 'abn_check'))),
            'errors' => array('abn_callable' => 'Invalid ABN has been entered %s.')
    )

); );

The form validation class attempting to be called is (ie $this->form_validation_callback_library): 尝试被调用的表单验证类为(即$ this-> form_validation_callback_library):

class Form_validation_callback_library
{

    public function abn_check()
    {

        $this->load->library('abn_validator');

        $abn = $this->input->post_get('abn', TRUE);

        if (!$this->abn_validator->isValidAbn($abn)) {
            return FALSE;
        }

        return TRUE;

    }


}

The controller is: 控制器是:

        $this->config->load('fvalidation');
        $validation_rules = $this->config->item('client_details');
        $this->form_validation->set_rules($validation_rules);               

        if ($this->form_validation->run() == FALSE) {
            // show form
        } else {
            // process form data
        }

Any help would be greatly appreciated. 任何帮助将不胜感激。

Cheers, VeeDee 干杯,VeeDee

I would use codeigniter callback example below callback 我将在回调下面使用codeigniter回调示例

http://www.codeigniter.com/user_guide/libraries/form_validation.html#callbacks-your-own-validation-methods http://www.codeigniter.com/user_guide/libraries/form_validation.html#callbacks-your-own-validation-methods

<?php

class Example extends CI_Controller {

public function index() {
    $this->load->library('form_validation'); 

    $this->form_validation->set_rules('client_abn', 'ABN Number', 'required|callback_checkabn');

    if ($this->form_validation->run() == FALSE) {

        $this->load->view('something');

    } else {

        // Redirect to success page i.e login or dashboard or what ever

        redirect('/'); // Currently would redirect to home '/'

    }
}

public function checkabn() {

    $this->load->library('abn_validator');

    $abn = $this->input->post('abn');

    if (!$this->abn_validator->isValidAbn($abn)) {
        $this->form_validation->set_message('checkabn', 'Invalid ABN has been entered %s.');
        return FALSE;
    } else {
        return TRUE;
    }

}

}

And on your view in or above form add 并在表格中或上方的视图中添加

<?php echo validation_errors('<div class="error">', '</div>'); ?>

<form action="<?php echo base_url('example');?>" method="post">
    <input type="text" name="client_abn" placeholder="" value="" />
</form>

This is a most common problem we face when we run custom form validation in CI. 当我们在CI中运行自定义表单验证时,这是我们面临的最常见问题。 Whether the callback function is in the same controller or it is in the a library of callback function we need to pass the accessible object of the class containing the callback function. 无论回调函数是在同一控制器中还是在回调函数库中,我们都需要传递包含回调函数的类的可访问对象。 So when your run the 因此,当您运行

$callable_validations = new Form_validation_callback_library();

$this->form_validation->run($callable_validations)

Looks like this is not possible currently on CodeIgniter 3. 看起来目前在CodeIgniter 3上无法实现。

I have created a crude workaround.. so please go ahead an improve it because it doesn't look pretty :) 我创建了一个粗略的解决方法..所以请继续对其进行改进,因为它看起来并不漂亮:)

Update the config file like so (/config/fvalidation.php): 像这样更新配置文件(/config/fvalidation.php):

$config['client_details'] =  = array(
        array(
                'field' => 'client_abn',
                'label' => 'Client ABN',
                'rules' => array('trim', 'required', array('abn_callable', array("library:form_validation_callback_library", 'abn_check'))),
                'errors' => array('abn_callable' => 'Invalid %s has been entered .')
        )
);

Note the following line in the config file above as we will be using them as flags in the controller code: 注意上面的配置文件中的以下行,因为我们将它们用作控制器代码中的标志:

array('abn_callable', array("library:form_validation_callback_library", 'abn_check'))

The Library is pretty much the same except we load the instance (/libraries/Form_validation_callback_library.php): 除了我们加载实例(/libraries/Form_validation_callback_library.php)外,库几乎相同。

class Form_validation_callback_library
{
    private $_CI;

    function Form_validation_callback_library() {
        $this->_CI =& get_instance();

        log_message('info', "Form_validation_callback_library Library Initialized");
    }

    public function abn_check($abn)
    {

        $this->_CI->load->library('abn_validator');


        if (!$this->_CI->abn_validator->isValidAbn($abn)) {
            return FALSE;
        }

        return TRUE;    
    }

}

In the controller we load the library (/controllers/Foo.php): 在控制器中,我们加载库(/controllers/Foo.php):

// load the config file and store
$this->config->load('fvalidation', TRUE);
$rule_dataset = $this->config->item('client_details', 'fvalidation');

// search and load the 'callable' library
foreach ($rule_dataset as $i => $rules) {
    if (isset($rules['rules'])) {
        foreach ($rules['rules'] as $k => $rule) {
            if (is_array($rule) && preg_match("/_callable/",$rule[0]) && isset($rule[1][0])) {                      
                list ($load_type, $load_name) = explode(":", $rule[1][0]);                      
                // load the library
                $this->load->$load_type($load_name);                        
                $rule_dataset[$i]['rules'][$k][1][0] = $this->$load_name;

            }
        }
    }           
}

// set the rules
$this->form_validation->set_rules($rule_dataset);

// load the form
if ($this->form_validation->run() == FALSE) {
  // show form
} else {
    // process form data
}

I did something similar to Vidura, but extended the Form Validation library by adding MY_Form_validation.php with the following code 我做了一些类似于Vidura的事情,但是通过添加MY_Form_validation.php和以下代码扩展了Form Validation库。

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class GS_Form_validation extends CI_Form_validation {

    public function set_rules($field, $label = '', $rules = array(), $errors = array())
    {
        if (is_array($rules))
        {
            foreach ($rules as &$rule)
            {
                if (is_array($rule))
                {
                    if (is_array($rule[1]) and is_string($rule[1][0]))
                    {
                        // handles rule like ['password_check', ['library:passwords', 'check_valid_password']]
                        // You would set_message like $this->form_validation->set_message('password_check', 'Incorrect password');
                        // The advantage of defining the rule like this is you can override the callback functions error message
                        list ($load_type, $load_name) = explode(":", $rule[1][0]);
                        $CI =& get_instance();
                        $CI->load->$load_type($load_name);
                        $rule[1][0] = $CI->$load_name;
                    }
                    else if (is_string($rule[0]))
                    {
                        // handles rule like ['library:password', 'check_valid_password']
                        // You would set_message like $this->form_validation->set_message('check_valid_password', 'Incorrect password');
                        list ($load_type, $load_name) = explode(":", $rule[0]);
                        $CI =& get_instance();
                        $CI->load->$load_type($load_name);
                        $rule[0] = $rule[1];
                        $rule[1] = [$CI->$load_name, $rule[1]];
                    }
                }
            }
        }

        return parent::set_rules($field, $label, $rules, $errors);
    }
}

Then you can define callbacks to library functions like: 然后,您可以定义对库函数的回调,例如:

$this->form_validation->set_rules(['library:passwords', 'check_valid_password']);

Where passwords is the library and check_valid_password is the method. 其中passwords是库,而check_valid_password是方法。

I've simply do (config/form_validation.php): 我只是做(config / form_validation.php):

$CI =& get_instance();
$CI->load->model('form_validation_callback_library');

$config['client_details'] = array(
    array(
            'field' => 'client_abn',
            'label' => 'Client ABN',
            'rules' => array('trim', 'required', array('abn_callable', array($CI->form_validation_callback_library, 'abn_check'))),
            'errors' => array('abn_callable' => 'Invalid ABN has been entered %s.')
    )

And it works to me... 它对我有用...

I'm running on Codeigniter 3.0.4 我在Codeigniter 3.0.4上运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM