Madhawa Ratnayake
Madhawa Ratnayake

Reputation: 189

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!

Upvotes: 5

Views: 17087

Answers (3)

MJ X
MJ X

Reputation: 9054

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/

Upvotes: 16

allen213
allen213

Reputation: 2277

You can get rid of the error by doing

(isset($gender)&&$gender=='Male'))

Also read http://www.codeigniter.com/user_guide/libraries/form_validation.html#re-populating-the-form

Upvotes: 0

claw68
claw68

Reputation: 374

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);

Upvotes: 1

Related Questions