• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
dynamic input field validation with inline error messages

#1
In my project, when I adding employee to system, I want to add history record for them if they are not newly recruit employee.
History records are dynamic input fields. Then its little bit difficult for me to do codigniter+Ajax form validation with inline error messages. I have attached screen shot what I have done so far.
can anyone pls tell me how to edit the private function _validate_add_new_emp() to validate dynamic input fields?

When I press the ADD button
<button type="button" class="btn-success btn-sm" id="btn_add_emp" onClick="add_emp()"> &nbsp;ADD</button>
////////////////////
function add_emp()
    {          
    var form = $('#form_new_emp')[0];
    var formData = new FormData(form);
   
        show_loading();
          $.ajax({
            url : "<?php echo site_url('index.php/User/add_new_emp')?>",     
            type: "POST",
            data: formData,
            contentType: false,
            processData: false,
            dataType: "JSON",
           
            success: function(data)
            {
                 if(data.status)
                        {             
                           location.reload();
                        }
                         else
                        {
                            hide_loading();
                            for (var i = 0; i < data.inputerror.length; i++)
                            {
                                $('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
                                $('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
                            }
                        }
            },
            error: function (jqXHR, textStatus, errorThrown)
            {
                 //how to display red coloured error msg when selected role already assigned
                alert('ERROR in ADDING NEW EMPLOYEE');
            }
        });    
    }
   ////////////////////////////////////
In my controller

public function add_new_emp() { 
$this-> _validate_add_new_emp();
     
$data = array(       
'emp_no' => $this->input->post('emp_no'),
'nic' => $this->input->post('nic'), // etc all the other fields goes here
)
$this->load->model('Model_user');
$this->Model_user->add_new_emp($data);
 $this->Model_user->saveToDatabase_history($data_history);
$this->session->set_flashdata('message', ' Successfully ADDED New Employee ......');
echo json_encode(array("status" => TRUE)); 
}
////////////////
this is how I do validations

  private function _validate_add_new_emp()
 {
  $data = array();
  $data['error_string'] = array();
  $data['inputerror'] = array();
  $data['status'] = TRUE;
  if($this->input->post('emp_no') == '')
  {
   $data['inputerror'][] = 'emp_no';
   $data['error_string'][] = 'Enter EMP NO.';
   $data['status'] = FALSE;
  }
  if($this->input->post('nic') == '')
  {
   $data['inputerror'][] = 'nic';
   $data['error_string'][] = 'Enter NIC';
   $data['status'] = FALSE;
  } // same as all the other fields goes here

if($data['status'] === FALSE)
  {
   echo json_encode($data);
   exit();
  }
 }

///////////the way I create dynamic text box for history
$("#historyButton").click(function () {
             $('#histryElement').show();
          });

        $("#addButton").click(function () {
   
            $('<div/>',{'id':'TextBoxDiv' + counter}).html(
                $('<label/>').html( 'Designation #' + counter + ' :&nbsp; ' ))
                    .append( $('<input type="text">').attr({'id':'post_history' + counter,'name':'post_history[]'}) ) 
                    .append( $('<label>&nbsp;&nbsp;&nbsp;&nbsp; From :  </label> <input type="date">').attr({'id':'date_from' + counter,'name':'date_from[]'}) )      
                    .append( $('<label>&nbsp;&nbsp;&nbsp;&nbsp; To :  </label> <input type="date">').attr({'id':'date_to' + counter,'name':'date_to[]'}) )
                    .appendTo( '#TextBoxesGroup' );
                    counter++;
        });

////////////////////////
In my Model, this is how I add history data to database. it works fine. but I'm unable to add validation.

public function saveToDatabase_history($data){
     
     if( isset( $data['post_history'] ) && is_array( $data['post_history'] ) ){
        foreach( $data['post_history'] as $key => $each ){
            $temp[] = array(
                        'emp_no'  =>$data['emp_no'],
                        'post_history'   =>$data['post_history'][$key],
                        'date_from' =>$data['date_from'][$key],
                        'date_to'=>$data['date_to'][$key],
                      );
        }
        if( isset( $temp ) ){
            $this->db->insert_batch('history', $temp);
          
        }
    }   
 }
Reply

#2
What does your post data look like?

Code:
public function add_new_emp() {  
    var_dump($_POST);
    die();
   // the rest of your code below
}

since you're using AJAX for that, will need to check the console/dev tools on your browser for the var_dump.

this will tell you what the server is receiving so you can figure out what/where you need to change the code (either to send data the server is expecting or change the server to work with the incoming data)
Reply

#3
(08-23-2017, 06:19 AM)Kaosweaver Wrote: What does your post data look like?

Code:
public function add_new_emp() {  
   var_dump($_POST);
   die();
  // the rest of your code below
}

since you're using AJAX for that, will need to check the console/dev tools on your browser for the var_dump.

this will tell you what the server is receiving so you can figure out what/where you need to change the code (either to send data the server is expecting or change the server to work with the incoming data)
 
I want to do the validation for dynamic input fields like this example.  http://formvalidation.io/examples/adding-dynamic-field/
I'm not submitting form using <button type="submit" class="btn btn-default">ADD</button>. 

When I press the ADD button with empty form data, it gives the inline error messages for all the fields except dynamic input fields.
I need to do something inside ajax function to validate dynamic input fields. May be handling array problem.I have no idea of doing it using ajax.

////this is how i add 

 private function _validate_add_new_emp()

{
if($this->input->post('post_history') == '')
{
$data['inputerror'][] = 'post_history';
$data['error_string'][] = 'Enter post_history';
$data['status'] = FALSE;
}
                
                 if($this->input->post('date_from') == '')
{
$data['inputerror'][] = 'date_from';
$data['error_string'][] = 'Enter date_from';
$data['status'] = FALSE;
}
                
                 if($this->input->post('date_to') == '')
{
$data['inputerror'][] = 'date_to';
$data['error_string'][] = 'Enter date_to';
$data['status'] = FALSE;
}

///In Model  I call the function like this

public function add_new_emp($data) {    
         
            $this->db->insert('emp_pmt', $data);
            return $this->db->insert_id(); 
    }

/////////In view ////
 <form action="#" class="form-horizontal" id="form_new_emp"> 
    
    <div class="form-group"> 
        <label class="col-sm-2 control-label">Emp No.</label> <div class="col-sm-2"> <label><input type="text" name="emp_no" id="emp_no" class="form-control"/><span class="help-block"></span></label></div>
        <label class="col-sm-1 control-label">NIC</label> <div class="col-sm-2"> <label><input type="text" name="nic" id="nic" class="form-control"/><span class="help-block"></span></label></div>
        <label class="col-sm-2 control-label">Personal File No.</label><div class="col-sm-2"><label><input type="text" name="file_no" id="file_no" class="form-control" /><span class="help-block"></span></label></div>
    </div>

<div class="form-group"> 
        <label class="col-xs-2 control-label" for="dob">DOB</label>  
        <div class="col-sm-2"><label><input type="date" name="dob" id="dob" class="form-control"><span class="help-block"></span> </label></div>
  </div>

<div class="form-group">
<label class="col-sm-2 control-label">Newly appoinment Employee?</label>  
<div class="col-xs-2">     
    <label class="radio"><input name="newly_app" id="newly_app" type="radio" value="Yes" onClick="hideNewApp()"> Yes</label> 
    <label class="radio"><input name="newly_app" id="newly_app" type="radio" value="No" onClick="showNewApp()"> No</label> 
</div><span class="help-block"></span>

<span id="history_label" style="visibility:hidden; margin:0">       
<div class="form-group">       
        <div class="col-md-3 ml-md-auto">                   
        <button type="button" class="btn-default btn-sm" id="historyButton" name="historyButton"> ADD NEW ENTRY FOR HISTORY</button>
        </div>     
</div>
         
     
                        <div id="histryElement">
                            <label class="control-label col-xs-2"> </label>
                            <div class="col-sm-9">
                                  <button type="button" class="btn-success btn-sm" id="addButton" name="addButton"> ADD</button>
                                  <button type="button" class="btn-danger btn-sm" id="removeButton" name="removeButton"> REMOVE</button>
                                  <br>
                                  <div id='TextBoxesGroup'>
                                    <div id="TextBoxDiv1">
                                        <br>
 <div class="form-group"> <label>Designation #1 :&nbsp; </label> <div class="col-xs-2"><label><input type='text' id='post_history1' name='post_history[]'> <span class="help-block"></span></label> </div> </div>
 <div class="form-group"> <label>&nbsp;&nbsp;&nbsp;From : &nbsp;</label> <div class="col-xs-2"><label> <input type='date' id='date_from1' name='date_from[]'><span class="help-block"></span></label> </div> </div>
 <div class="form-group"> <label>&nbsp;&nbsp;&nbsp;To :&nbsp;&nbsp; </label> <div class="col-xs-2"><label> <input type='date' id='date_to1' name='date_to[]'> <span class="help-block"></span></label> </div> </div>
                                    
                                    </div>
                                   </div>
                                  
                                <span class="help-block"></span>
                            </div>
                        </div>  
</span>

<span class="help-block"></span> 
</div>
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


Users browsing this thread:
1 Guest(s)


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2017 MyBB Group.