Search code examples
codeigniterreusability

How to reuse form in codeigniter for update and add


Hello i want to reuse a form in codeigniter but problem is the update form is populated one the page has load. Here is a sample form.

 <?php 
  $attributes = array('class' => 'form-horizontal', 'id' => 'addPersonnel');
  echo form_open($form_submission, $attributes);
  ?>
        <input type="text" name="name" value="<?php echo set_value('name')?"> >
        <input type="text" name="rank" value="<?php echo set_value('rank')?"> >
        <button type="submit" class="btn btn-primary">Save</button>                                                 
  <?php echo form_close()?>

My problem here lies in the set_value() method of the form_validation class since it will have conflict with populating the form if updating.


Solution

  • In your controller update function add a condition like:

    if ($this->input->server('REQUEST_METHOD') === 'POST') {
        $this->_get_userinfo_form_fields();
    } else {
        $this->_get_userinfo_form_fields($user_data); //$user_data from database
    }
    

    For add function you can directly call - $this->_get_userinfo_form_fields();

    Then declare a function as below:

    protected function _get_userinfo_form_fields($user_data = array()) {
        $this->data['rank'] = array(
            'placeholder' => 'Rank',
            'name'        => 'rank',
            'id'          => 'rank',
            'class'       => '',
            'value'       => isset($user_data['rank']) ? $user_data['rank'] :set_value('rank',$this->input->post('rank',TRUE)),
            'style'       => '',
        );
    
        //Add rest of the fields here like the above one
    }
    

    In view file add code like:

     <?php echo form_input($rank);?>