Codeigniter 3表格:提交后保存数据

问题描述:

I am making a customers CRUD application with Codeigniter 3. The "Add Customer" form view looks like this:

<div class="form-group <?php if(form_error('first_name')) echo 'has-error';?>">
    <?php echo form_input('first_name', '', [
        'type'  => 'text',
        'id'    => 'first_name', 
        'class' => 'form-control',
        'value' => '',
        'placeholder' => 'First name',
        ]); 
    ?>
    <?php echo form_error('first_name'); ?>                                     
</div>

The form also has validation on some of the text fields. I wish the data that is imputed, if data is invalid, would stay after submit. What shall I add to the code above?

我正在使用Codeigniter创建客户CRUD应用程序3.“添加客户”表单视图 em >看起来像这样: p>

 &lt; div class =“form-group&lt;?php if(form_error('first_name'))echo'has-error';?&gt  ;“&gt; 
&lt;?php echo form_input('first_name','',[
'type'=&gt;'text',
'id'=&gt;'first_name',
'class'  =&gt;'form-control',
'value'=&gt;'',
'占位符'=&gt;'名字',
]);  
?&gt; 
&lt;?php echo form_error('first_name');  ?&GT;  
&lt; / div&gt; 
  code>  pre> 
 
 

该表单还对某些文本字段进行了验证。 我希望估算的数据如果数据无效 em>,将在提交后保留。 我应该在上面的代码中添加什么? p> div>

According to the Codeigniter 3 official documentation, this is how the code should look in order for the input fields data to be kept if the form is not submitted:

<?php echo form_input('first_name', set_value('first_name'), [
   'type'  => 'text',
   'id'    => 'first_name', 
   'class' => 'form-control',
   'placeholder' => 'First name',
]);?>   

In your form_input function, Set value key as set_value() for text fields , set_select() for select , set_checkbox() for checkbox and set_radio() for radio button. This will repopulate your from after submitting the form even if the page is refreshed. See below example for your first name text field, where i put value as set_value('first_name'). this function set the posted value there after validation put the form back.

You can see more validation rules here

   <div class="form-group <?php if(form_error('first_name')) echo 'has-error';?>">
<input type="text" id="first_name" class="form-control" value="<?php echo set_value('first_name');?>" placeholder="First name" />

        <?php echo form_error('first_name'); ?>                                     
    </div>

And on your controller, you must set the first_name in validation rule like below

  $this->form_validation->set_rules('first_name', 'First name', 'required');

You must set this rules for each field even if it is not required or dont have any rules. You can also leave the rules parameter blank.

As I know you can do 2 things on here

  1. Use AJAX
  2. Use session

Using AJAX means you can check filed validation + from validation and then SUBMIT the form. So your data remain till last.

Or

Save it to session when submitting and the after redirect load it back to respective fields.