2012-03-11 67 views

回答

1

我找到了答案。它涉及使用2個回調函數攔截set_rules()中的值。我刪除了這篇文章的代碼,以便更容易理解。

的配置文件:

// This is where the default text will come from so it's easy to modify 
// The second config (['address']) is there just to show that ['test'] is an array 
$config['test']['name'] = 'Default Text'; 
$config['test']['address'] = 'Some other text'; 

規則:

// The sample rule. Do not add 'required' in the rules since _sanitize already 
// does the checking for blank values. Insert the name of the field 
// within the []. _sanitize() needs to be called before _check(). 
$this->form_validation->set_rules('name', 'Name', 'trim|callback__sanitize[name]|callback__check[name]'); 

的2回調函數:_sanitize()和_check()

// CALLBACK: _sanitize 
/* 
* If field is empty(), inserts the default value found in the config file 
* Works alongside _check(). 
*/ 
public function _sanitize($str, $arg){ 
    if(empty($str)){ 
    $text = $this->config->item('test'); 
    return $text[$arg]; 
    } 

    // If !empty(), return the value as if nothing happened 
    return $str; 
} 

// CALLBACK: _check 
/* 
* If value is equivalent to the default value (from the config file), mark it as FALSE 
* Works alongside _sanitize(). 
*/ 
public function _check($str, $arg){ 
    $text = $this->config->item('test'); 

    if($str == $text[$arg]){ 
    $this->form_validation->set_message('_check', 'The %s field is required'); 
    return FALSE; 
    } 

    return TRUE; 
} 

最後,查看代碼:

// Put at top of page 
<?php 
$name = array(
    'name'=>'name', 
    'value'=>set_value('name'), 
    'class'=>"form-text", 
    'maxlength'=>200 
); 
?> 

// Put within the page 
<?php echo form_input($name); ?>