5

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

12
  • there is no <form> tag. Can you reduce the question to a small problem? Without context, it's hard to know what goes where Commented Aug 11, 2016 at 21:20
  • what is your codeigniter version ? Commented Aug 11, 2016 at 21:33
  • @motto The version is 3.0.6 Commented Aug 11, 2016 at 22:16
  • Answered your question, please add the code for add button Commented Aug 12, 2016 at 1:37
  • Also, when adding inputs, do you add all three again? Commented Aug 12, 2016 at 1:50

5 Answers 5

3

First of all , You are using incomplete input selector in form. It should be like this..

 <input type="text" name="detail[]" required>

In codeigniter code. Use simple php isset and count function on posted array from form. By this you can validate the posted array. Form validation library working every where as you want. Condition for posted data.

    if(isset($_POST['detail']) && (count($_POST['detail'])>0)){
    // code here
    }
    else{
     return "required";
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Do I use your if statement in the validation callback function?
Sorry for late reply..Its working fine anywhere you want .. Also one more thing, By this way you can send easily different different type error messages @bobthegoalie .
@bobthegoalie are u get your answer??
2
+50

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

1 Comment

I am trying to use your if statement but it does not like when I use [] behind the name. Do you have a suggestion of how to identify the field?
2

After trying my best to understand it all, Here is what I can say.

First, all your inputs does not have it's closing > and required doesn't need to have that "" part.

<input type="text" name="detail[]" required=""

change all to

<input type="text" name="detail[]" required>

Next, Your callback in codeigniter, I'm assuming the code is to check if all has inputs. You do not need this is you do what I said above.

Lastly, I'm missing the part when you dynamically add an input, add that code and I'll have a look at it more. But doing what I said, you will not be able to submit the form using HTML5 validations.

This won't refresh the page nor submit the form if either one is empty

2 Comments

If you need more help in a more complete code, I'm more than willing to answer it.
I am actually not submiting the form. I am calling the function add_quotation and grabbing the post data by serializing the form. So the required method would not work if I am correct. I added the code for adding a table row.
1
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>'); 
$this>form_validation>set_rules('detail','Detail','required|greater_than[0]');
if ($this->form_validation->run() == FALSE) {
   $this->load->view('',$data);
}else{
   $this->model->add()
}

Comments

1

I found an easy way my own,

some simple javascript

I tend to use my validation in the controller without using a the form_validation() method

example is:

    //this is a model
    public function login($username,$password){
    $data = array('username' => $username,
    'password' => $password);

    $query = $this->db->select('user_account',$data);

    return $query->result_array();
    }

    //view
    <form action = "" method = "post">
    <input type = "text" name = "username"/>
    <input type = "password" name = "password"/>
    <button>Submit</button>
    </form>


    //this is the controller
    public function logging_in(){
    $username = $this->input->post('username');
    $password = $this->input->post('password');

    $result = $this->model->login($username,$password);

            if(empty($username) && empty($password)){

            echo "<script>alert('Empty!');</script>";
            }
            else{
                    if($result!=NULL){
                    echo "<script>alert('Successfully Logged In!');</script>";
                    }
            }

    }

You can call the method in controller via:

    <?php echo form_open('User_Authentication/logging_in'); ?>
    //Your form
    <?php echo form_close(); ?>

Or you can use this:

    <form action = "<?php echo base_url(); ?>index.php/User_Authentication/logging_in" method="post">

Try with this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.