How to clear form after submit in Codeigniter?

Member

by lottie , in category: PHP Frameworks , 2 years ago

How to clear form after submit in Codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by dana , a year ago

@lottie 

To clear a form after it has been submitted in Codeigniter, you can use the reset_form() method of the Form Validation library. This method will reset all form data to its original state.


Here's an example of how you can use reset_form() in a controller:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Load the Form Validation library
$this->load->library('form_validation');

// Validate the form submission
if ($this->form_validation->run() == TRUE) {
    // Form is valid, do something here (e.g., save to database)

    // Reset the form data
    $this->form_validation->reset_form();
}


Alternatively, you can simply redirect the user to the same form page after the form is submitted, which will also clear the form data.

1
2
3
4
// Form is valid, do something here (e.g., save to database)

// Redirect the user back to the form page
redirect('form');


Note that you will need to load the Form Validation library before you can use the reset_form() method. You can do this by using the load->library() method, as shown in the first example above.

by giovanny.lueilwitz , 10 months ago

@lottie 

In Codeigniter, you can clear the form after submission in the following steps:

  1. Create a function in your controller file to handle form submission. For example, in your controller file (e.g. MyController.php), you can have:
1
2
3
4
5
6
7
public function submitForm() {
    // Handle form submission
    // ...

    // Clear form input
    redirect('myController/displayForm');
}


  1. In the same controller file, create a function to display the form. For example:
1
2
3
4
5
6
7
public function displayForm() {
    // Load form helper
    $this->load->helper('form');

    // Load your view file (e.g. form_view.php)
    $this->load->view('form_view');
}


  1. In your view file (e.g. form_view.php), you can use the form_open() function from the form helper to create the form. For example:
1
2
3
4
5
6
    
    

    


With this setup, when the user submits the form, the submitForm() function will be called and after processing the form submission, it will redirect back to the displayForm() function. This will reload the form view, effectively clearing the form inputs.