php Codeigniter 表单验证 - 如何在成功后取消设置表单值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/2802046/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Codeigniter Form Validation - how to unset form values after success?
提问by BrynJ
I realise this request goes against the example provided in the CI documentation (which advises a separate 'success' page view), but I would like to reutilise a given form view after a form has been successfully submitted - displaying a success message then displaying a blank form. I've tried a few ways unsuccessfully to clear the validation set values (unsetting $_POST, setting rules / fields to an empty array and rerunning validation).  
我意识到此请求与 CI 文档中提供的示例(它建议单独的“成功”页面视图)背道而驰,但我想在成功提交表单后重新利用给定的表单视图 - 显示成功消息,然后显示空白表格。我尝试了几种方法来清除验证集值(取消设置$_POST,将规则/字段设置为空数组并重新运行验证),但均未成功。  
I could redirect to the same page, but then I'd have to set a session variable to display a success message - which is a messy approach.
我可以重定向到同一页面,但随后我必须设置一个会话变量来显示成功消息 - 这是一种混乱的方法。
Any ideas how to best achieve the above?
任何想法如何最好地实现上述目标?
回答by Teej
Redirect to itself. This way, no submissions have been run... This also gives you a way to show the flash_data.
重定向到自身。这样,没有提交已经运行...这也给你一种方式来显示flash_data。
    $this->load->library('form_validation');
    $this->form_validation->set_rules('firstname', 'First Name', 'required');
    $this->form_validation->set_rules('surname', 'Sur Name', 'required');
    if ($this->form_validation->run() === TRUE)
    {
                    // save data
        $this->session->set_flashdata('message', 'New Contact has been added');
        redirect(current_url());
    }
    $this->load->view('contacts/add', $this->data);
回答by d5avard
Another solution, extend the library CI_Form_validation. The property $_field_datais protected, so we can acces it:
另一种解决方案,扩展库CI_Form_validation。该属性$_field_data受到保护,因此我们可以访问它:
class MY_Form_validation extends CI_Form_validation {
    public function __construct()
    {
        parent::__construct();
    }
    public function clear_field_data() {
        $this->_field_data = array();
        return $this;
    }
}
And call the new method. This way, you can pass data without storing data in session.
并调用新方法。这样,您可以在不将数据存储在会话中的情况下传递数据。
    class Item extends Controller
    {
        function Item()
        {
            parent::Controller();
        }
        function add()
        {
            $this->load->library('form_validation');
            $this->form_validation->set_rules('name', 'name', 'required');
            $success = false;
            if ($this->form_validation->run())
            {
                $success = true;
                $this->form_validation->clear_field_data();
            }
            $this->load->view('item/add', array('success' => $success));
        }
    }
回答by bschaeffer
Pass a TRUE/FALSE variable to your views that conditionally sets the values of the form.
将 TRUE/FALSE 变量传递给有条件地设置表单值的视图。
The Controller
控制器
if($this->form_validation->run())
{
    $data['reset'] = TRUE;
}
else
{
    $data['reset'] = FALSE:
}
$this->load->view("form", $data);
The View:
风景:
<input type="text" name="email" value="<?php echo ($reset) ? "" : set_value('email'); ?>" />
<input type="text" name="first_name" value="<?php echo ($reset) ? "" : set_value('first_name'); ?>" />
回答by Stephen Curran
The set_value function fetches its value from the Form_validation object and not from the $_POST array. The Form_validation object stores its own copy of the posted values in a variable called $_field_data.
set_value 函数从 Form_validation 对象而不是 $_POST 数组中获取其值。Form_validation 对象在一个名为 $_field_data 的变量中存储它自己的已发布值的副本。
Its a hack, but you could clear this variable after handling a successful submission :
它是一个黑客,但您可以在处理成功提交后清除此变量:
class Item extends Controller
{
    function Item()
    {
        parent::Controller();
        $this->load->model('item_model');
    }
    function add()
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('name', 'name', 'required');
        $success = false;
        if ($this->form_validation->run())
        {
            $this->item_model->add_item($this->input->post('name'));
            $success = true;
            // Look away now. Hack coming up!
            // Clear the form validation field data
            $this->form_validation->_field_data = array();
        }
        $this->load->view('item/add', array('success' => $success));
    }
}
回答by dt teja
Hope this would be helpful. Finally I understand the whole concept of the extending the library. All you need to do is 
Step 1: In this directory "application/libraries/" create a file named "MY_Form_validation.php" with the following php code
希望这会有所帮助。最后我理解了扩展库的整个概念。您需要做的就是
第 1 步:在此目录“application/libraries/”中,使用以下 php 代码创建一个名为“MY_Form_validation.php”的文件
<?php if (!defined('BASEPATH')) exit('No direct script access allowed.');
class MY_Form_validation extends CI_Form_validation {
 public function MY_Form_validation() {
    parent::__construct();
  }
  public function unset_field_data()
    {    
        unset($this->_field_data);    
    }
}
Step 2:Then use the function "unset_field_data()" in you controller. for example below:
第 2 步:然后使用unset_field_data()控制器中的功能“ ”。例如下面:
    if ($this->form_validation->run())
    {
        $this->item_model->add_item($this->input->post('name'));
        $success = true;
        $this->form_validation->unset_field_data();
    }
回答by quinny
I've found that where:
我发现在哪里:
- there's more than one CI view-partials which make up the page and their controller methods perform validation
 - one of the validations failed and produced an error since the last page-refresh, say with an incorrectly formatted or typed input field value
 
- 构成页面的 CI 视图部分不止一个,它们的控制器方法执行验证
 - 自上次页面刷新以来,其中一个验证失败并产生错误,例如格式或输入的输入字段值不正确
 
it isn't enough to clear only the validation-rules array, you need to clear the validation-error array too.
仅清除验证规则数组是不够的,您还需要清除验证错误数组。
To this end, I've added a method to system/libraries/Form_Validation.php, as follows:
为此,我在system/libraries/Form_Validation.php中添加了一个方法,如下:
public function clear_rules()
{
    $this->_error_array = array();
    $this->_field_data = array();
    return $this;
}
Returning $this is important if you want to chain your form-validation methods.
如果您想链接表单验证方法,则返回 $this 很重要。
回答by Bhunesh Satpada
In newer version 3.X, to clear set_value , $_POST=array()and $this->_field_data = array();in MY_Form_validation.phplibrary. try 
在新版本3.X,以明确SET_VALUE,$_POST=array()并$this->_field_data = array();在MY_Form_validation.php库中。尝试
Clear form data after success codeigniter using php not jquery
回答by pgee70
The answer from d5avard is wrong, the CI form validation should have the rules array parsed to it: If you don't do this you can use form validation with posted data, but not with over-ride data.
d5avard 的答案是错误的,CI 表单验证应该将规则数组解析为它:如果您不这样做,您可以对发布的数据使用表单验证,但不能使用覆盖数据。
save this file as Libraries/MY_Form_validation.php
将此文件保存为 Libraries/MY_Form_validation.php
    /**
     * Class MY_Form_validation
     * @description extension of the CI_Form_validation
     * @property CI_DB_query_builder db database driver
     * @property CI_Benchmark benchmark
     * @property CI_Input input
     * @property CI_Output output
     */
    class MY_Form_validation extends CI_Form_validation
    {
        /**
         * MY_Form_validation constructor.
         * @param array $rules
         */
        function __construct($rules = array())
        {
            parent::__construct($rules);
            $this->_error_prefix        = '<div class=""><p>';
            $this->_error_suffix        = '</p></div>';
        }
        /**
         * Resets the form validation class for multiple runs.
         * @param array $rules
         */
        public function initialise($rules = array())
        {
            if (count($rules) == 0 )
            {
                require (APPPATH.'config'.DIRECTORY_SEPARATOR.'form_validation.php');
                $this->_config_rules = $config;
            }
            else
            {
                $this->_config_rules = $rules;
            }
            $this->_field_data          = array();
            $this->_error_array         = array();
            $this->_error_messages      = array();
            $this->_error_prefix        = '<div class=""><p>';
            $this->_error_suffix        = '</p></div>';
            $this->error_string         = '';
        }
    }

