Welcome Guest, Not a member yet? Register   Sign In
Repopulate a form after submission
#1

I have been using codeigniter for a while and I am really enjoying it. However, I have faced a development learning curve because I am trying to figure out how I would go about repopulating a form after a user submitted it. For example, I currently have a form where a user enters information into the fields for a product, then clicks submit, then goes through the model and inserts into the database, then is returned back to the home page with a success message. What I would like to create is a mechanism so when the user clicks on submit they are given an option to submit a similar product then have the fields be prepopulated with the last information they inserted. How would I go about doing this or what would be the best way. Should I repopulated the fields for the last entries from the database? Could I retain the previous POST data from the last form and fill it in, I am confused on this. Any suggestions or guidance would be much appreciated.
Reply
#2

Hi

You can repopulate the form with CI easily please refer this
http://www.codeigniter.com/user_guide/li...latingform

I recommend that you should have those fields validated and repopulate. To me it work hand in hand flawlessly

Regards
Reply
#3

Here's how I do it.

In the view file:
PHP Code:
<input type="text" id="price" name="product[price]" value="<?= set_value('product[price]') ?>"/> 

I always use arrays for my form values, and I send the array to the form inside the $data array when loading the view. Something like this in my product controller file:
PHP Code:
public function add_product()
{
 
   $message 'Enter product and click Submit button';
 
   $product = array(
 
       'name' => '',
 
        'price' => 0,
 
        'description' => ''
 
   );
 
   // $this->form_validation->set_rules goes here
    if ($this->form_validation->run())
 
   {
 
       $product $this->input->post('product');
        $data = array (
            'name' => $product['name'],
 
           'price' => $product['price'],
 
           'description' => $product['description']
 
         );
        $this->products_model->add($data);
 
       $message 'Success! Enter another if you wish';
 
   }
 
   else
    
{
 
       if (validation_errors())
 
       {
 
            $message validation_errors();
 
            $product $this->input->post('product');
 
       }
 
   }
    $data = array (
 
       'message' => $message,
 
       'product' => $product
    
);
    $this->load->view('add_product_view'$data);

  
This way, the same view is used to both enter products and confirm success. The view shows the $message variable, which as you can see, can contain three different messages. The product array is first blank/zeros for the first time the form loads. After that, whether there's an error or not, it will contain what the user entered in the form.

The above is very stripped down, but let me know if it doesn't make sense.
Reply
#4

Okay I am still a little confused on how to implement this because current I have the following in my controller:
PHP Code:
public function insertEntry()
 {
 
//validation rules from product info
 //I had a lot of validation rules here

 
if($this->form_validation->run() == FALSE) {
 
$data['main_content'] = 'query_forms/insert_product';
 
$this->load->view('layouts/main',$data); 
 }
 else
 { 
 if (
$this->Product_model->insert_product_info()) {
 
$this->session->set_flashdata('done''Successfully added a product to the JAM database');
 
redirect('home/index');
 }
 else
 {
 
$this->session->set_flashdata('error''An error occured submitting to the database!');
 
redirect('home/index');
 }

 } 
 } 


Then I had my view like the following:
PHP Code:
<h1>Add a New Product into the Jam Database</h1>
<
p>Please fill out the form below to add the new product</p>

<!--
Display Form Errors-->
<?
php echo validation_errors('<p class="alert alert-dismissable alert-danger">'); ?>
<?php 
echo form_open('dbqueries/insertEntry'); ?>

<!-- Field for original approved date || Make sure to change to a datetime picker-->
<p>
<?php echo form_label('Original Approved Date: '); ?>
<?php 
$opts 
'placeholder="e.g: 2010-04-30"';
$data = array('name'=>'original_approved_date''value'=>set_value('original_approved_date'));?>
<?php 
echo form_input($data''$opts); ?>
</p>

<!-- Field for approved by-->
<p>
<?php echo form_label('Approved By: '); ?>
<?php 
$opts 
'placeholder="name"';
$data = array('name'=>'approved_by''value'=>set_value('approved_by'));?>
<?php 
echo form_input($data,''$opts); ?>
</p>

<!-- Field for revise date-->
<p>
<?php echo form_label('Revision date: '); ?>
<?php
$opts 
'placeholder="e.g: 2010-04-30"';
$data = array('name'=>'revise_date''value'=>set_value('revise_date'));?>
<?php 
echo form_input($data''$opts);?>
</p>

<!-- Field for revise approval date-->
<p>
<?php echo form_label('Revision approval date: '); ?>
<?php
$opts 
'placeholder="e.g: 2010-04-30"';
$data = array('name'=>'revision_approval_date''value'=>set_value('revision_approval_date'));?>
<?php 
echo form_input($data,'',$opts);?>
</p> 

<!-- Field for revision approved by-->
<p>
<?php echo form_label('Revision approved by: '); ?>
<?php
$opts 
'placeholder="name"';
$data = array('name'=>'revision_approved_by''value'=>set_value('revision_approved_by'));?>
<?php 
echo form_input($data''$opts);?>
</p>

<!-- Field for style name-->
<p>
<?php echo form_label('Style name: '); ?>
<?php
$opts 
'placeholder="Holiday Shoe & Headband Set"';
$data = array('name'=>'style_name''value'=>set_value('style_name'));?>
<?php 
echo form_input($data''$opts);?>
</p> 

<!-- Field for style number-->
<p>
<?php echo form_label('Style number: '); ?>
<?php
$opts 
'placeholder="SH555WR"';
$data = array('name'=>'style_number''value'=>set_value('style_number'));?>
<?php 
echo form_input($data''$opts);?>
</p> 

<!-- Field for lot number-->
<p>
<?php echo form_label('Lot number: '); ?>
<?php
$opts 
'placeholder="100"';
$data = array('name'=>'lot''value'=>set_value('lot'));?>
<?php 
echo form_input($data''$opts);?>
</p> 

//and many more fields

<!--Submit Buttons-->
<?php $data = array("value" => "Submit",
"name" => "submit",
"class" => "btn btn-primary"); ?>
<p>
<?php echo form_submit($data); ?>
</p>
<?php echo form_close(); ?>

So right now the button submits to the database. So if I am still confused on how to implement a second button allow the user to submit another product with similar properties. Or in other words after submitting the first product be brought back to the form with the fields repopulated from the first entry.
Reply
#5

For what you really want to happen then go with ajax post from view, I had similar project done such as products are similar or same attributes
and adding them with same refilling attributes are cumbersome. This is how I solve it

Assume you have form with all fields to submit then you can bypass the default behaviour like this jquery snippet

$('form').on('submit', function(e){
e.preventDefault(); //will stop refresh page or reload
var data_submitted = $(this).serialize();
var url_to_process = 'controller/action'; //point to where the action is
//Here is the post action
$.post(url_to_process, data_submitted, function(result){
console.info(JSON.stringify(result)); //optional callback json so you can debug or do something with them!
},'json');
});

Note url_to_process is where you submit information to for processing data and result is json output as result callback. I suggest
you may like to build a simple form and use this approach to see how it works then scale it up to meet your expectation.

I may have a controller for action like this

class Product extends CI_Controller{
function __construct(){
parent::__construct();
}
function insert(){
$post_data = $this->input->post(NULL,TRUE); // this will be all your input fields array data from view
//action to save to dB tables coding ....
// write you code here ....
//assume success saving return then we may have
$b_saving_data = $this->product_model->saveAll($post_data);
if($b_saving_data){
print json_encode('success'=>1, 'message'=>'OK', 'data'=>$post_data ); //OR you can pass anything in 'data' as call back to //view
}


}
}/*END CLASS*/

Hope this gives you some guidelines for your project.
Reply
#6

(12-30-2014, 01:44 PM)jonathantkids Wrote: So right now the button submits to the database. So if I am still confused on how to implement a second button allow the user to submit another product with similar properties. Or in other words after submitting the first product be brought back to the form with the fields repopulated from the first entry.

You don't need a second button. You use the same form with the same button. Let me see if I can walk you through the code I posted.
PHP Code:
public function add_product()
{
 
   $message 'Enter product and click Submit button';
 
   $product = array(
 
       'name' => '',
 
        'price' => 0,
 
        'description' => ''
 
   );
 
   // $this->form_validation->set_rules goes here
 
   if ($this->form_validation->run())
 
   {
 
       $product $this->input->post('product');
 
       $data = array (
 
           'name' => $product['name'],
 
           'price' => $product['price'],
 
           'description' => $product['description']
 
         );
 
       $this->products_model->add($data);
 
       $message 'Success! Enter another if you wish';
 
   }
 
   else // form validation failed OR first time through
 
   {
 
       if (validation_errors())
 
       {
 
            $message validation_errors();
 
            $product $this->input->post('product');
 
       }
 
   }
 
   $data = array (
 
       'message' => $message,
 
       'product' => $product
    
);
 
   $this->load->view('add_product_view'$data);

Say it's the first time through the function. No products entered so far. The code sets $message to "Enter product and click Submit." The code also sets up a $product array with blanks/zeroes. Then the code sets up the form validation rules.

But the first time through, form validation will fail because nothing has even been submitted, so the code falls down to the else clause. Now, the code doesn't know if validation failed because nothing was submitted (first time through) or because there really was a validation error, so the code checkes the validation_errors function. If there is even one validation error, the if statement will be true, and the code will then load $message with the error messages and load $product with whatever the user entered in the form. It does this so it can show the user what he or she entered.

Then, the $data array gets loaded with whatever is in $message and $product, and the code then loads the view, sending it the $data array. The view then shows whatever is in $message as well as using the values in the $product array to populate the form fields with set_values().

After the users submits the form, it's a similar process, except this time, either validation will succeed or it will fail because of errors (either way, something was posted). If validation succeeded, the code loads the $data array with the values to save in the database and calls the add function in the model file. Notice that it does not redirect anywhere! Instead, having added the row to the database, the code falls through to the last few lines, where the $data array is loaded with $message and $product and the same view is called.

As long as you keep pressing the Submit button, the code will keep adding another row to the database. In fact, you'll need some code to prevent entering two identical products. You can restrict that at the database, or you can write code that holds the last entry and compares it to the next. 

Now, I hope I understood your question correctly. You want your user to fill out a form, press Submit, and after the code adds the row to the database, you want your user to once again see the same form, but this time with the information he or she entered before, so that if the next product is basically the same, except size medium instead of size small, and $3.49 instead of $2.25, your user won't have to fill out the entire form again. Did I get that right?

It also occurred to me that you may have to use the second argument of set_values:
PHP Code:
value="<?= set_value('product[name]', $product['name']) ?>" 
Without the dollar sign, product[name] is just the name of the field. Usually that's all you need because Codeigniter automatically saves the values of the fields (it just doesn't set those values automatically). But I believe Codeigniter clears the field values when form validation succeeds, so to populate the form, you'll need the data in $product['name'].
Reply
#7

(This post was last modified: 12-31-2014, 08:36 PM by jonathantkids.)

Okay, so I found a simple solution very similar to RobertSF. In my view I added an extra submit button so there are two submit buttons in the view like so:
PHP Code:
<!--Submit Buttons-->
<?
php $data = array("value" => "Submit",
"name" => "submit",
"class" => "btn btn-primary"); ?>
<p>
<?php echo form_submit($data); ?>
</p>
<p>
<?php echo form_submit('submit_another'' Submit and Enter a Similar Item ''class="btn btn-warning btn-lg"'); ?>
</p> 

Then in the model I just added the code like the following:
PHP Code:
        if($this->form_validation->run() == FALSE) {
            
$data['main_content'] = 'query_forms/insert_product';
            
$this->load->view('layouts/main',$data);    
        }
        else
        {
            if (!empty(
$_POST['submit'])) {
                  
// submit button pressed
                
if ($this->Product_model->insert_product_info()) {
                    
$this->session->set_flashdata('done''Successfully added a product to the JAM database');
                    
redirect('home/index');
                }
            }    
            if (!empty(
$_POST['submit_another'])) {
                  
// submit button pressed
                
if ($this->Product_model->insert_product_info()) {
                    
$this->session->set_flashdata('done''Successfully added a product to the JAM database');
                    
$data['main_content'] = 'query_forms/insert_product';
                    
$this->load->view('layouts/main',$data);    
                }
            }    
            else
            {
                
$this->session->set_flashdata('error''An error occured submitting to the database!');
                
redirect('home/index');
            }

        } 

And that seemed to do the trick. But thanks for the suggestions and help everyone! Smile
Reply
#8

Great! I'm glad to hear you've solved your problem! Smile
Reply




Theme © iAndrew 2016 - Forum software by © MyBB