我知道set_value()
如果它未能通过验证,它会用于填充表单。但是如果该字段是empty()
(这就是它失败的原因)可以 set_value() 插入一个默认值吗?
问问题
1905 次
1 回答
1
我找到了答案。它涉及set_rules()
使用 2 个回调函数截取值。我删除了这篇文章的代码,以便更容易理解。
配置文件:
// 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); ?>
于 2012-03-11T18:58:46.107 回答