CodeIgniter form validation, re-populating dynamically added fields
Make a provision of index on each of your form element.
<form action="" method="post"> <input type="text" name="name[1]"> <input type="text" name="name[2]"></form>
So, your JS becomes like,
counter = 3;$('#add').click(function(){ $('form').append('<input type="text" name="name['+counter+']">'); counter++;}
Now, if your validation fails, you have to add condition like:
<form action="" method="post"><?php if ($this->form_validation->run() == FALSE) { foreach($this->input->post('name') as $ind=>$item) { ?> <input type="text" name="name[<?php echo $ind ?>]" value="<?=set_value('name[".$ind ."]');?>"> <?php } } else { ?> <input type="text" name="name[1]"> <input type="text" name="name[2]"> <?php }?></form>
Ok, how I did it:
The Controller
<?php$data['some_data'] = ''; // Some data from the database to send to the viewif($this->form_validation->run() == FALSE){ // Posted? if($this->input->post()) { // Merge the submitted data with the current data $data = array_merge($this->input->post(),$data); } // Load the view $this->load->view('view',$data);}else{ // Code after validation was successfull}
The view
<? if(isset($name)): // Name set? ?> <? foreach($name as $item): // Loop through all previous posted items ?> <input type="text" name="name[]" value="<?=set_value('name[]'); // Set it's value with the regular set_value function ?>"> <? endforeach; ?><? else: ?> <input type="text" name="name[]"><? endif; ?>
This way it isn't hacky with controller stuff in the view and it works perfectly!
@hsuk, thanks!