Pergunta

I have a form that has its fields dynamically added as such:

function addFieldRow() {
  $('.form-container').append('
    <div><input type="text" name="name[1]"></div>
    <div>
      <select name="choice[1]">
        <option value="red">red</option>
        // . . .
      </select>
    </div>
     // . . .
  ');
}

I then pass these to its respective CodeIgniter controller with the declared array form_validation rules:

$this->form_validation->set_rules('name[]', 'text field', 'required');
// . . . other fields' rules

The problem is that if any of the dynamically added forms have an error, these are gone during the view loading. I want to know if how can I preserve the dynamically added form fields after the validation run with errors:

if ($this->form_validation->run() == FALSE) {
  // do stuff to preserve the dynamically created fields to show their errors
  $this->load->view('user_addresses_view');
}

Better solution

I have found the solution to preserve these dynamically added elements by using ajax to connect to the form's respective controller in the CodeIgniter framework. This method can:

  1. Do client-side and server-side validation without refreshing the page
  2. Since the page does not refresh, all these dynamically added form elements will not disappear!

Solution by james246

Foi útil?

Solução

you can't do it because page is actually refreshing and row is added client side so when validation done then you will redirected to same page with validation errors you will not see dynamically added dom because as i said it was happend client side not in your code...so all you can do is use session and then at load time manually validate and add them to page.

Using SESSION might not be good idea because for that you will have to code more complex helpers and validation methods and etc...

Other possible solution

  1. use jQuery.validate plugin that allow us to validate dynamically added rows ( fields , dom ).

  2. take benefit of mysql and add those field into database with possible error stored in db and send it to view file.

Outras dicas

In view :

 for($i=0; $i<$ttl_input;$i++)
    {
    <div><input type="text" name="name[".$i."]"></div>
    <?php echo form_error('name['.$i.']'); ?>
    }

in controller:

foreach($this->input->post('name') as $index=>$name)
{
$this->form_validation->set_rules('name['.$index.']', 'text field', 'required');
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top