Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter: How can I retain values after an invalid form submission?

I've Googled and there are many ways of doing this in PHP itself, JavaScript/ jQuery/ AJAX and CodeIgniter session data/ flash data.

But I prefer to have do this within PHP. My form is very large and contains different elements like text inputs, dropdowns, radios, etc. However I tried the following on my inputs in the View (MVC).

Example:

< input type="radio" name "gender" value="Male" <?php echo ($gender == 'Male')? 'checked': ''; ? />
< input type="radio" name "gender" value="Female" <?php echo ($gender == 'Female')? 'checked': ''; ? />

This gives an error on page load, obviously because the $gender variable is not defined. I can fix this issue in Controller but it will be a huge process and fragment the code. Are there any alternative ways? Examples are welcome!

like image 685
Madhawa Ratnayake Avatar asked Jul 08 '13 09:07

Madhawa Ratnayake


People also ask

How can we store form data in database using CodeIgniter?

First, you must create a PHP page in View directory of CodeIgniter, in which a form is created using CodeIgniter's syntax. Second, you have to create class in Controller directory, in which the above PHP page(view) is loaded, applying validation over form fields and respective model is loaded.

What is Set_value in CodeIgniter?

The set_value function just sets the value, the only benefit to using it is it simplifies setting the value to an already submitted value when redisplaying the form or showing a default value when the form has yet to be submitted.

What is form validation in CodeIgniter?

CodeIgniter lets you set as many validation rules as you need for a given field, cascading them in order, and it even lets you prep and pre-process the field data at the same time. To set validation rules you will use the set_rules() method: $this->form_validation->set_rules();


2 Answers

codeigniter has set_value you just type your input name inside like example blow. if the validation false it just retain the values you entered before. example:

 <input type='text' name='last_name' id='last_name' value="<?=set_value('last_name')?>" />

and complete documentation is here.

http://www.codeigniter.com/user_guide/libraries/

like image 106
MJ X Avatar answered Oct 03 '22 20:10

MJ X


add the post data to your view data warning: this is a dirty and lazy way to do it according to your problem and your code:

example:

on the controller where you submit it:

function submit(){
 $data->post = $this->input->post();
 $this->load->view('view', $data);
}

on the view add this:

extract($post);
like image 29
claw68 Avatar answered Oct 03 '22 20:10

claw68