【问题标题】:Codeigniter: How to build an edit form that uses form validation and re-population?Codeigniter:如何构建使用表单验证和重新填充的编辑表单?
【发布时间】:2011-02-13 18:25:22
【问题描述】:

我在 codeigniter 中有一个简单的表单,希望用于编辑或记录。 我正处于显示我的表单并将值输入到相应输入框中的阶段。

只需将所述框的值设置为视图中所需的值即可:

<input type="text" value="<?php echo $article['short_desc'];?>" name="short_desc" />

但是,如果我想在 codeigniter 中使用 form_validation,那么我必须将这些代码添加到我的标记中:

<input value="<?php echo set_value('short_desc')?>" type="text" name="short_desc" />

因此,如果需要根据发布数据的错误重新填充该值,则不能使用 set_value 函数设置该值。

有没有办法将两者结合起来,以便我的编辑表单可以显示要编辑的值但也可以重新填充?

谢谢

【问题讨论】:

    标签: validation codeigniter


    【解决方案1】:

    set_value() 实际上可以使用第二个参数作为默认值,如果没有要重新填充的内容(至少查看 CI 版本 1.7.1 和 1.7.2)。请参阅 Form_validation.php 库中的以下内容(第 710 行):

    /**
     * Get the value from a form
     *
     * Permits you to repopulate a form field with the value it was submitted
     * with, or, if that value doesn't exist, with the default
     *
     * @access  public
     * @param   string  the field name
     * @param   string
     * @return  void
     */ 
    function set_value($field = '', $default = '')
    {
        if ( ! isset($this->_field_data[$field]))
            {
                return $default;
            }
    
            return $this->_field_data[$field]['postdata'];
    }
    

    因此,考虑到这一点,您应该能够像这样简单地将默认值传递给 set_value:

    <input value="<?php echo set_value('short_desc', $article['short_desc'])?>" type="text" name="short_desc" />
    

    如果没有要重新填充的值,set_value() 将默认为 $article['short_desc']

    希望对您有所帮助。

    【讨论】:

    • 完美解决方案。在测试此“set_value”时,请将“set_value()”函数应用于所有字段。在单个字段上测试它不会产生结果。
    猜你喜欢
    • 2010-11-10
    • 1970-01-01
    • 2012-07-12
    • 1970-01-01
    • 2014-10-10
    • 2012-05-05
    • 1970-01-01
    • 2018-12-12
    • 2010-12-30
    相关资源
    最近更新 更多