Codeigniter:如何构建使用表单验证和重新填充的编辑表单?

Ser*_*gio 10 validation codeigniter

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

这可以通过简单地将所述框的值设置为视图中需要的任何值来完成:

<input type="text" value="<?php echo $article['short_desc'];?>" name="short_desc" />
Run Code Online (Sandbox Code Playgroud)

但是,如果我希望在codeigniter中使用form_validation,那么我必须在我的标记中添加代码:

<input value="<?php echo set_value('short_desc')?>" type="text" name="short_desc" />
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢

Col*_*ock 19

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'];
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

希望有所帮助.