【问题标题】:Codeigniter: Insert string if set_value() is emptyCodeigniter:如果 set_value() 为空,则插入字符串
【发布时间】:2012-03-11 17:17:52
【问题描述】:

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

【问题讨论】:

    标签: codeigniter setvalue


    【解决方案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]');
    

    两个回调函数:_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); ?>
    

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 1970-01-01
      • 2020-10-03
      • 1970-01-01
      • 2019-03-09
      • 2020-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多