bobthegoalie bobthegoalie - 3 months ago 16
PHP Question

Codeigniter Validate Array In Form

I have a form with a table. The table includes three user inputs. Quantity, Line Items, and a Price. I need all three to be filled in before a user can submit the form. The table allows for rows to be added.

Here is my table.

<form id="add_quote_form" name="add_quote_form" class="form-horizontal">
<table style="width: 90%" id="myTable" class="centered-table table table-bordered">
<thead>
<tr>
<th>Item</th>
<th>Qty</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td style="width: 60%"><input type="text" name="detail[]"required></td>
<td style="width: 10%"><input type="number" name="qty[]" required></td>
<td style="width: 15%"><input type="number" name="price[]" required></td>
<td style="width: 12%"><div class="inline"><input type="button" id="addButton" class="btn btn-primary btn-xs" value="Add"/></div><div class="inline"><input type="button" id="deleteButton" class="btn btn-primary btn-xs" value="Delete"/></div>
</tr>
</tbody>
</table>
<input type="button" id="saveBtn" name="saveBtn" class="btn btn-primary" value="Create Order" onClick="this.disabled=true; add_quotation();return false;">
</form>


Function to add row to table

$(function(){
$("#addButton").click(function(){
$(this).closest("tr").clone(true).appendTo("#myTable");
});

$("#deleteButton").click(function(){
// var x = document.getElementById("myTable").rows.length;
var x = $('#myTable tr').length;
if(x == 2){

} else {
$(this).closest("tr").remove();
}

});
});


Function called on submit button

function add_quotation() {
document.add_quote_form.saveBtn.value="Saving...";
var formArray = $('#add_quote_form').serialize();

jQuery.post('<?php echo base_url(); ?>index.php/quotes/add_work_order_validation/' , formArray, function(data)
{
//alert('here');

if (data.success)
{
//GetQuotesPage();
//location.reload(base_url+'quotes');
//window.location = base_url+'quotes';
document.add_quote_form.saveBtn.value="Save Order";
document.add_quote_form.saveBtn.disabled=false;
swal({


title: "Order Saved!",
// text: "You clicked the button!",
type: "success"
});
//alert("Quote Saved");
}
else
{
document.add_quote_form.saveBtn.value="Save Order";
document.add_quote_form.saveBtn.disabled=false;
for (var i in data.errors)
{
$('#'+i).css('border-color', 'red');
$('#'+i).validationEngine('showPrompt', data.errors[i], '', 'topRight', true);
}
for (var z in data.hidden)
{
$('#add_quote_form#' +data.hidden[z]).validationEngine('hide');
}
}
}, 'json');

return false;
}


Here is my controller

public function add_work_order_validation()
{


$this->form_validation->set_rules('quoteName', 'Quote Name', 'trim|required');
$this->form_validation->set_rules("dueDate", "Due Date", "trim|required");
$this->form_validation->set_rules('detail[]', 'Line Items','required|trim|callback_matchLineItems');


if ($this->form_validation->run() == FALSE)
{
$result['errors'] = array();
$result['hidden'] = array();
$result['success'] = false;
$fields = array('quoteName', "dueDate", "detail");

foreach ($fields as $field)
{
if (form_error($field))
{
$result['errors'][$field] = strip_tags(form_error($field));
}
else
{
$result['hidden'][] = $field;
}
}
}
else
{ //Post Form
}


And the final part my callback function

function matchLineItems() {

$detailArray = $this->input->post("detail");
$qtyArrayPost = $this->input->post("qty");
$priceArray = $this->input->post("price");
$qtyNumberCount = count($qtyArrayPost);
$priceNumberCount = count($priceArray);
$detailNumberCount = count($detailArray);

if($qtyNumberCount != $priceNumberCount || $qtyNumberCount != $detailNumberCount || $detailNumberCount != $priceNumberCount) {
$this->form_validation->set_message('matchLineItems', 'No Fields Can Be Left Blank');
return FALSE;
} else {
return TRUE;
}

}


The issue that I am having is when I leave the line items field blank, the form does not submit but no error is shown. If I enter data into the line items field but leave the qty and price field empty, the form submits. Do I need to create validation for each field in the table? How do I get the errors to appear?

Codeigniter version 3.0.6

Answer

For a field like

<input type="text" class="form-control" id="firstname" name="firstname" placeholder="Guest's First Name">

Add a simple tag like the below one

<p class="firstname_error error"></p>

and then check using jquery

var firstname = $('#firstname').val(); 
if(firstname == '' || firstname == null)
            {
                valid = false;
                $(".firstname_error").html("* Firstname is required");
            }
            else
            {
                $(".firstname_error").html(""); 
            }

and the add you main part using a condition

if(valid==true){

//your main jquery code
}

Also if you are using CI method for form validation you must specify the location like

<?php echo form_error('username'); ?>
<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />

as mention here on its tutorials https://www.codeigniter.com/userguide3/libraries/form_validation.html#showing-errors-individually

With the limited details for testing here is the workaround for your code https://jsfiddle.net/kmvgty/napz948b/1/

have just added an id for each tab and have js something like

$('#saveBtn').on('click', function() {
  var detail = $('#detail').val();
  var qty = $('#qty').val();
  var price = $('#price').val();
  if ((detail == '') || (detail == null)) {
    valid = false;
    $('#erropr').removeClass('hide');
    $('#erropr').html('* Enter an item');

  } else {
    $('#erropr').html('');
  }

  // same way for other
});

Ofcourse your scenario would be different but this is just a suggestion look to the fiddle if it can help you out

Comments