Codeigniter:如果set_value()为空,则插入字符串

时间:2012-03-11 17:17:52

标签: codeigniter setvalue

我了解set_value()用于在表单验证失败时填充表单。但是如果字段是empty()(这就是失败的原因),set_value()可以插入一个默认值吗?

1 个答案:

答案 0 :(得分: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); ?>