laravel mutliple row save to database - javascript

I am a laravel beginner. Currently i am learning to do an inventory system. I have two table: goodsreceiveheader and goodsreceivedetail.
What can i do to allow multiple row save into database when submit button are clicked. Hope somebody will help me out as i had stuck in this for a few weeks=(
For goodsreceiveheader table, i have the field of:
id,
referencenumber,
vendorid(FK),
date,
createdby.
While goodsreceivedetail table, i have the field of:
id,
goodsreceiveheader_id(FK),
itemid(FK),
quantity,
costprice.
create.blade.php
#extends('admin.layout')
#section('content')
<fieldset>
<legend>Create New Goods Receive</legend>
#include('layouts.error')
{!! Form::open(['url' => 'goodsreceive/save', 'method'=>'post']) !!}
#include('goodsreceiveheader.partial._goodsreceiveheader_form')
{!! Form::close() !!}
</fieldset>
#endsection
My view:
<style>
div#gr{
padding: 20px;
border:1px solid black;
}
</style>
<div class="container">
<h2>Goods Receive</h2>
<hr>
<div id="gr" class="row" style="background-color: lightgoldenrodyellow">
<div class="col-lg-4 col-sm-6">
<input name="createdby" type="hidden" value="{{ Auth::user()->name }}">
{!! Form::label('referencenumber', 'Reference Number:')!!}
<div class="form-group">
<input type="text" name="referencenumber" class="form-control" placeholder="Reference Number">
</div>
</div>
<div class="col-lg-4 col-sm-6">
{!! Form::label('date', 'Receive Date:')!!}
{!! Form::date('date',null,['class'=>'form-control']) !!}
</div>
<div class="col-lg-4 col-sm-6">
{!! Form::label('vendorid', 'Vendor ID:')!!}
<select name="vendorid" class="form-control">
<option value="" selected disabled>Please Select Vendor..</option>
#foreach($vendors as $vendor)
<option value="{{$vendor->id}}">{{$vendor->vendorid}}</option>
#endforeach
</select>
</div>
</div>
<br>
<table class="table table-bordered">
<thead>
<th>Item Barcode</th>
<th>Quantity</th>
<th>Cost Price</th>
<th style="text-align: center;background: #eee">
<a href="#" onclick="addRow()">
<i class="glyphicon glyphicon-plus"></i>
</a>
</th>
</thead>
<tbody>
<tr>
<td>
<select class="form-control" name="itemid">
<option value="" selected disabled>Select Barcode</option>
#foreach($items as $item)
<option value="{{$item->itemid}}">{{$item->itembarcode}}</option>
#endforeach
</select>
</td>
<td><input type="text" name="quantity" class="form-control quantity"></td>
<td><input type="text" name="costprice" class="form-control costprice"></td>
<td style="text-align: center" onclick="cannotdelete()">
<a href="#" class="btn btn-danger remove">
<i class="fa fa-times"></i>
</a>
</td>
</tr>
</tbody>
</table>
<br>
<button type="submit" class="btn btn-primary pull-right">Submit</button>
</div>
<script type="text/javascript">
function addRow()
{
var tr='<tr>'+
'<td>'+
'<select class="form-control" name="itemid">'+
'<option value="" selected disabled>Select Barcode</option>'+
'#foreach($items as $item)'+
'<option value="{{$item->itemid}}">{{$item->itembarcode}}</option>'+
'#endforeach'+
'</select>'+
'</td>'+
'<td><input type="text" name="quantity" class="form-control quantity"></td>'+
'<td><input type="text" name="costprice" class="form-control costprice"></td>'+
'<td class="remove" style="text-align: center"><i class="fa fa-times"></i></td>'+
'</tr>';
$('tbody').append(tr);
}
function deleteRow()
{
$(document).on('click', '.remove', function()
{
$(this).parent('tr').remove();
});
}
function cannotdelete()
{
alert('You cannot delete the first row!!!')
}
</script>
My controller:
public function save(GoodsreceiveheaderRequest $request)
{ $data = array(
'referencenumber'=>$request->referencenumber,
'vendorid'=>$request->vendorid,
'date'=>$request->date,
'createdby'=>$request->createdby,
);
$i = DB::table('goodsreceiveheader')->insertGetId($data);
$goodsreceivedetail = array(
'goodsreceiveheader_id'=>$i,
'itemid'=>$request->itemid,
'quantity'=>$request->quantity,
'costprice'=>$request->costprice,
);
$s = DB::table('goodsreceivedetail')->insert($goodsreceivedetail);
Session::flash('message','You have successfully create goods receive.');
return redirect('goodsreceive/goodsreceiveheader_list');
}

use insert function and pass your data as multiple array like
if model name is 'User' then below code will work for multiple entry
User::insert(['name'=>'xyz'],['name'=>'abc']);

Solved.
public function save(GoodsreceiveheaderRequest $request)
{
$head = Goodsreceiveheader::findorNew($request->id);
$head->referencenumber=$request->referencenumber;
$head->vendorid=$request->vendorid;
$head->date=$request->date;
$head->createdby=$request->createdby;
if ($head->save()){
$id = $head->id;
foreach($request->itemid as $key =>$item_id){
$data = array(
'goodsreceiveheader_id'=>$id,
'itemid'=>$request->itemid [$key],
'quantity'=>$request->quantity [$key],
'costprice'=>$request->costprice [$key],
);
Goodsreceivedetail::insert($data);
}
}
Session::flash('message','You have successfully create goods receive.');
return redirect('goodsreceive/goodsreceiveheader_list');
}

Related

OnChange Not Working in cloned Input fields

I have created a form and in the form I have given room to clone input fields ie add or delete rows.
In one input field I am using Jquery Ajax to get the value.
Unfortunately after adding an additional role ie cloning the parent row to get a child row, ajax does not pass the value for the input field expecting it value from the Ajax.
I have attached the code below to explain better
function restrictAlphabets(e) {
var x = e.which || e.keyCode;
if ((x >= 48 && x <= 57))
return true;
else
return false;
}
// Below Clones Table
document.querySelector('button[data-name="add"]').addEventListener('click', e => {
let tbody = e.target.closest('table').querySelector('tbody');
let clone = tbody.firstElementChild.cloneNode(true);
clone.querySelector('button[data-name="del"]').hidden = false;
clone.querySelectorAll('input, select').forEach(n => {
n.value = '';
});
tbody.appendChild(clone);
});
document.querySelector('form table#dyntbl').addEventListener('click', e => {
e.stopPropagation();
if (e.target != e.currentTarget && (e.target.dataset.name == 'del' || e.target.parentNode.dataset.name == 'del')) {
let tbody = e.target.closest('table').querySelector('tbody');
if (tbody.childNodes.length > 3) tbody.removeChild(e.target.closest('tr'))
}
});
// Below begins AJAX Function
function checkDeviceStatus() {
var dModel = $("#model").val();
var dBrand = $("#brand").val();
var dserial = $("#serialNo").val();
var client = $("#client").val();
$.ajax({
url: "./handlers/slaChecker.php",
type: "POST",
data: {
dModel: dModel,
dserial: dserial,
client: client,
dBrand: dBrand,
},
success: function(result) {
$("#deviceLevel").val(result);
console.log(result);
}
})
}
<div class="col-xl-8 col-md-12">
<form>
<div class="card">
<div class="card-header">
<h3 class="card-title"><strong class="text-success" style="cursor: pointer;"><?=ucwords($clientName)?></strong> REP'S INFORMATION</h3>
</div>
<div class="card-body">
<div class="row">
<div class="col-sm-4 col-md-4">
<div class="form-group">
<label class="form-label">Reps Name<span class="text-red">*</span></label>
<input type="text" name="" class="form-control" required="">
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="form-group">
<label class="form-label">E-Mail<span class="text-red">*</span></label>
<input type="email" name="" class="form-control" required="">
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="form-group">
<label class="form-label">Phone No.<span class="text-red">*</span></label>
<input type="text text-dark" class="form-control" name="client_contact2" required="" id="client_contact2" onkeypress="return restrictAlphabets(event)" onpaste="return false;" ondrop="return false;" autocomplete="off" required="">
<input type="date" name="" value="<?=date(" Y-m-d ")?>" hidden="">
</div>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<h3 class="card-title">ADD DEVICE(S) INFORMATION</h3>
</div>
<div class="card-body">
<?php
if ($clientType === $slaClient) {
?>
<table id='dyntbl' class='table border text-nowrap text-md-nowrap table-striped mb-0'>
<thead>
<tr>
<th class="text-center">Device Brand</th>
<th class="text-center">Device Model</th>
<th class="text-center">Serial Number</th>
<th class="text-center" style="width:10%">SLA Device</th>
<th><button type="button" class=" btn text-success" data-name='add'><i class="fe fe-plus-circle" data-id='ad' style="font-size:1.6em;"></i></button></th>
</tr>
</thead>
<tbody class="field_wrapper " id="table_body">
<tr>
<td>
<select class="form-control form-select " data-bs-placeholder="Select" name="brand[]" required="" id="brand" onchange="checkDeviceStatus()">
<?php
$readALL = "SELECT * FROM productbrands WHERE deleted = 0";
$displayAll = mysqli_query($conn,$readALL);
while($rowFetchAll = mysqli_fetch_array($displayAll)){
$brandName = $rowFetchAll['brandName'];
$brandid = $rowFetchAll['brandID'];
?>
<option value="<?=$brandid?>">
<?=$brandName?>
</option>
<?php } ?>
</select>
</td>
<td>
<select class="form-control form-select " data-bs-placeholder="Select" name="model[]" required="" id="model" onchange="checkDeviceStatus()">
<?php
$readALL1 = "SELECT * FROM productmodels WHERE deleted = 0";
$displayAll1 = mysqli_query($conn,$readALL1);
while($rowFetchAll1 = mysqli_fetch_array($displayAll1)){
$modelName = $rowFetchAll1['modelName'];
$modelid = $rowFetchAll1['modelID'];
?>
<option value="<?=$modelid?>">
<?=$modelName?>
</option>
<?php } ?>
</select>
</td>
<td><input type="text" name="serialNo" class="form-control" id="serialNo" onchange="checkDeviceStatus()"></td>
<!-- The input field below is to get value from AJAX -->
<td><input type="text" name="deviceLevel" class="form-control" readonly="" id="deviceLevel">
<!-- End of Input field -->
</td>
<input type="text" name="" id="client" value="<?=$clientID?>" hidden="">
<td><button type="button" class=" btn text-danger" data-name="del"><i class="fe fe-minus-circle" style="font-size:1.6em;"></i></button></td>
</tr>
</tbody>
</table>
<?php } ?>
<?php
if ($clientType === $nonSla) {
?>
<table id='dyntbl' class='table border text-nowrap text-md-nowrap table-striped mb-0'>
<thead>
<tr>
<th>Product Model Non-SLA</th>
<th>Serial Number Non-SLA</th>
<th>Device Status Non-SLA</th>
<th><button type="button" class=" btn text-success" data-name='add'><i class="fe fe-plus-circle" data-id='ad' style="font-size:1.6em;"></i></button></th>
</tr>
</thead>
<tbody class="field_wrapper " id="table_body">
<tr>
<td><input type="text" name="" class="form-control"></td>
<td><input type="text" name="" class="form-control"></td>
<td><input type="text" name="" class="form-control"></td>
<td><button type="button" class=" btn text-danger" data-name="del"><i class="fe fe-minus-circle" style="font-size:1.6em;"></i></button></td>
</tr>
</tbody>
</table>
<?php } ?>
</div>
</div>
</form>
</div>
The main problem is that when you clone, you will get duplicated id's. An Id must always be unique.
I would suggest that you change the ID to class or something else and do something like this.
function checkDeviceStatus(obj) {
var dModel = $(obj).closest("tr").find(".model").val();
var dBrand = $(obj).closest("tr").find(".brand").val();
var dserial = $(obj).closest("tr").find(".serialNo").val();
var client = $(obj).closest("tr").find(".client").val();
console.log("dserial:"+dserial);
//Removed ajax for demo.
}
And then add this to your onchange="checkDeviceStatus()" like onchange="checkDeviceStatus(this)"
Demo
function restrictAlphabets(e) {
var x = e.which || e.keyCode;
if ((x >= 48 && x <= 57))
return true;
else
return false;
}
// Below Clones Table
document.querySelector('button[data-name="add"]').addEventListener('click', e => {
let tbody = e.target.closest('table').querySelector('tbody');
let clone = tbody.firstElementChild.cloneNode(true);
clone.querySelector('button[data-name="del"]').hidden = false;
clone.querySelectorAll('input, select').forEach(n => {
n.value = '';
});
tbody.appendChild(clone);
});
document.querySelector('form table#dyntbl').addEventListener('click', e => {
e.stopPropagation();
if (e.target != e.currentTarget && (e.target.dataset.name == 'del' || e.target.parentNode.dataset.name == 'del')) {
let tbody = e.target.closest('table').querySelector('tbody');
if (tbody.childNodes.length > 3) tbody.removeChild(e.target.closest('tr'))
}
});
// Below begins AJAX Function
function checkDeviceStatus(obj) {
var dModel = $(obj).closest("tr").find(".model").val();
var dBrand = $(obj).closest("tr").find(".brand").val();
var dserial = $(obj).closest("tr").find(".serialNo").val();
var client = $(obj).closest("tr").find(".client").val();
console.log("dserial:"+dserial);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-xl-8 col-md-12">
<form>
<div class="card">
<div class="card-header">
<h3 class="card-title"><strong class="text-success" style="cursor: pointer;"><?=ucwords($clientName)?></strong> REP'S INFORMATION</h3>
</div>
<div class="card-body">
<div class="row">
<div class="col-sm-4 col-md-4">
<div class="form-group">
<label class="form-label">Reps Name<span class="text-red">*</span></label>
<input type="text" name="" class="form-control" required="">
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="form-group">
<label class="form-label">E-Mail<span class="text-red">*</span></label>
<input type="email" name="" class="form-control" required="">
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="form-group">
<label class="form-label">Phone No.<span class="text-red">*</span></label>
<input type="text text-dark" class="form-control" name="client_contact2" required="" id="client_contact2" onkeypress="return restrictAlphabets(event)" onpaste="return false;" ondrop="return false;" autocomplete="off" required="">
<input type="date" name="" value="<?=date(' Y-m-d ')?>" hidden="">
</div>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<h3 class="card-title">ADD DEVICE(S) INFORMATION</h3>
</div>
<div class="card-body">
<?php
if ($clientType === $slaClient) {
?>
<table id='dyntbl' class='table border text-nowrap text-md-nowrap table-striped mb-0'>
<thead>
<tr>
<th class="text-center">Device Brand</th>
<th class="text-center">Device Model</th>
<th class="text-center">Serial Number</th>
<th class="text-center" style="width:10%">SLA Device</th>
<th><button type="button" class=" btn text-success" data-name='add'><i class="fe fe-plus-circle" data-id='ad' style="font-size:1.6em;">ADD</i></button></th>
</tr>
</thead>
<tbody class="field_wrapper " id="table_body">
<tr>
<td>
<select class="form-control form-select brand" data-bs-placeholder="Select" name="brand[]" required="" id="" onchange="checkDeviceStatus(this)">
<?php
$readALL = "SELECT * FROM productbrands WHERE deleted = 0";
$displayAll = mysqli_query($conn,$readALL);
while($rowFetchAll = mysqli_fetch_array($displayAll)){
$brandName = $rowFetchAll['brandName'];
$brandid = $rowFetchAll['brandID'];
?>
<option value="<?=$brandid?>">
<?=$brandName?>
</option>
<?php } ?>
</select>
</td>
<td>
<select class="form-control form-select model" data-bs-placeholder="Select" name="model[]" required="" id="" onchange="checkDeviceStatus(this)">
<?php
$readALL1 = "SELECT * FROM productmodels WHERE deleted = 0";
$displayAll1 = mysqli_query($conn,$readALL1);
while($rowFetchAll1 = mysqli_fetch_array($displayAll1)){
$modelName = $rowFetchAll1['modelName'];
$modelid = $rowFetchAll1['modelID'];
?>
<option value="<?=$modelid?>">
<?=$modelName?>
</option>
<?php } ?>
</select>
</td>
<td><input type="text" name="serialNo" class="form-control serialNo" onchange="checkDeviceStatus(this)"></td>
<!-- The input field below is to get value from AJAX -->
<td><input type="text" name="deviceLevel" class="form-control" readonly="" id="deviceLevel">
<!-- End of Input field -->
</td>
<input type="text" name="" class="client" value="<?=$clientID?>" hidden="">
<td><button type="button" class=" btn text-danger" data-name="del"><i class="fe fe-minus-circle" style="font-size:1.6em;"></i></button></td>
</tr>
</tbody>
</table>
<?php } ?>
<?php
if ($clientType === $nonSla) {
?>
<table id='dyntbl' class='table border text-nowrap text-md-nowrap table-striped mb-0'>
<thead>
<tr>
<th>Product Model Non-SLA</th>
<th>Serial Number Non-SLA</th>
<th>Device Status Non-SLA</th>
<th><button type="button" class=" btn text-success" data-name='add'><i class="fe fe-plus-circle" data-id='ad' style="font-size:1.6em;"></i></button></th>
</tr>
</thead>
<tbody class="field_wrapper " id="table_body">
<tr>
<td><input type="text" name="" class="form-control"></td>
<td><input type="text" name="" class="form-control"></td>
<td><input type="text" name="" class="form-control"></td>
<td><button type="button" class=" btn text-danger" data-name="del"><i class="fe fe-minus-circle" style="font-size:1.6em;"></i></button></td>
</tr>
</tbody>
</table>
<?php } ?>
</div>
</div>
</form>
</div>
I have found solution to it.
The classes as you all suggested wasn't Ideal instead this is what I did.
the ids has to be unique so I created a variable for it to be handling the additional ids.
This worked perfectly for me.
Php is now working fine and Ajax is also working fine.
$(document).ready(function() {
var num = 1;
var c = `
<tr id="row_num" >
<td>
<select class="form-control form-select brand" data-bs-placeholder="Select" name="brand[]" required="" id="brand_num" onchange="checkDeviceStatus(_num)">
<?php
$readALL = "SELECT * FROM productbrands WHERE deleted = 0";
$displayAll = mysqli_query($conn,$readALL);
while($rowFetchAll = mysqli_fetch_array($displayAll)){
$brandName = $rowFetchAll['brandName'];
$brandid = $rowFetchAll['brandID'];
?>
<option value="<?=$brandid?>"><?=$brandName?></option>
<?php } ?>
</select>
</td>
<td>
<select class="form-control form-select model" data-bs-placeholder="Select" name="model[]" required="" id="model_num" onchange="checkDeviceStatus(_num)">
<?php
$readALL1 = "SELECT * FROM productmodels WHERE deleted = 0";
$displayAll1 = mysqli_query($conn,$readALL1);
while($rowFetchAll1 = mysqli_fetch_array($displayAll1)){
$modelName = $rowFetchAll1['modelName'];
$modelid = $rowFetchAll1['modelID'];
?>
<option value="<?=$modelid?>"><?=$modelName?></option>
<?php } ?>
</select>
</td>
<td><input type="text" name="serialNo" class="form-control serialNo" id="serialNo_num" onkeyup="checkDeviceStatus(_num)"></td>
<!-- The input field below is to get value from AJAX -->
<td>
<input type="text" name="deviceLevel" class="form-control " readonly="" id="deviceLevel_num">
<!-- End of Input field -->
</td>
<td><button type="button" onclick="DeleteRow(_num)" class=" btn text-danger remove" data-name="del"><i class="fe fe-minus-circle" style="font-size:1.6em;"></i></button></td>
</tr>
`;
$(".addRow").click(function(e) {
var cc = c;
// e.preventDefault();
cc = cc.replace('_num', num);
cc = cc.replace('_num', num);
cc = cc.replace('_num', num);
cc = cc.replace('_num', num);
cc = cc.replace('_num', num);
cc = cc.replace('_num', num);
cc = cc.replace('_num', num);
cc = cc.replace('_num', num);
cc = cc.replace('_num', num);
$(".table_body").append(cc);
num++;
console.log(num);
});
});
<tbody class="field_wrapper showRow table_body" id="table_body">
<tr id="row0">
<td>
<select class="form-control form-select" data-bs-placeholder="Select" name="brand[]" required="" id="brand0" onchange="checkDeviceStatus(0)">
<?php
$readALL = "SELECT * FROM productbrands WHERE deleted = 0";
$displayAll = mysqli_query($conn,$readALL);
while($rowFetchAll = mysqli_fetch_array($displayAll)){
$brandName = $rowFetchAll['brandName'];
$brandid = $rowFetchAll['brandID'];
?>
<option value="<?=$brandid?>">
<?=$brandName?>
</option>
<?php } ?>
</select>
</td>
<td>
<select class="form-control form-select " data-bs-placeholder="Select" name="model[]" required="" id="model0" onchange="checkDeviceStatus(0)">
<?php
$readALL1 = "SELECT * FROM productmodels WHERE deleted = 0";
$displayAll1 = mysqli_query($conn,$readALL1);
while($rowFetchAll1 = mysqli_fetch_array($displayAll1)){
$modelName = $rowFetchAll1['modelName'];
$modelid = $rowFetchAll1['modelID'];
?>
<option value="<?=$modelid?>">
<?=$modelName?>
</option>
<?php } ?>
</select>
</td>
<td><input type="text" name="serialNo" class="form-control " id="serialNo0" onkeyup="checkDeviceStatus(0)"></td>
<!-- The input field below is to get value from AJAX -->
<td><input type="text" name="deviceLevel" class="form-control " readonly="" id="deviceLevel0">
<!-- End of Input field -->
</td>
<input type="text" name="" id="client" value="<?=$clientID?>" hidden="">
<td><button type="button" class=" btn text-success addRow" data-name='add'><i class="fe fe-plus-circle " data-id='ad' style="font-size:1.6em;"></i></button></td>
</tr>
</tbody>

Dynamic row calculation with Jquery

I want to make sum of dynamic rows and addition.
<div class="row">
<div class="col-md-8">
<div class="table-responsive">
<table id="test-table" class="table table-bordered">
<thead>
<tr>
<th>Product</th>
<th>Price </th>
<th><input id='add-row' class='btn btn-primary' type='button' value='Add' /> </th>
</tr>
</thead>
<tbody id="test-body">
<tr id="row0" class="products">
<td>
<select name="product_id[]" id="" class="form-control">
<option value="">-- Select Product --</option>
#foreach ($product as $row )
<option value="{{ $row->id }}">{{ $row->product_name }}</option>
#endforeach
</select>
</td>
<td>
<input name="price[]" type="number" min="1" class="form-control input-md price" />
</td>
<td>
<input class="delete-row btn btn-primary" type="button" value="Delete" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="col-md-4">
<div class="col-xs-6">
<p>Previous Due</p>
</div>
<div class="col-xs-6">
<input type="text" class="form-control" value="5000" readonly>
</div>
<div class="col-xs-6">
<p>Total Price</p>
</div>
<div class="col-xs-6">
<input type="text" class="form-control total_price" value="" readonly>
</div>
<div class="col-xs-6">
<p>Pay Now</p>
</div>
<div class="col-xs-6">
<input type="number" class="form-control">
</div>
<div class="col-xs-6">
<p>Total Due</p>
</div>
<div class="col-xs-6">
<input type="number" value="" class="form-control">
</div>
</div>
</div>
Script:
<script type="text/javascript">
var row=1;
$(document).on("click", "#add-row", function () {
var new_row = '<tr id="row' + row + '" class="products"><td> <select name="product_id[]' + row + '" id="" class="form-control"> <option value="">-- Select Product --</option> #foreach ($product as $row ) <option value="{{ $row->id }}">{{ $row->product_name }}</option>#endforeach </select></td><td><input name="price[]' + row + '" type="number" min="1" class="form-control price" /></td><td><input class="delete-row btn btn-primary" type="button" value="Delete" /></td></tr>';
$('#test-body').append(new_row);
row++;
return false;
});
$(document).on("click", ".delete-row", function () {
if(row>0) {
$(this).closest('tr').remove();
row--;
}
return false;
});
</script>
<script type="text/javascript">
function sumIt() {
var total = 0, val;
$('.price').each(function() {
val = $(this).val();
val = isNaN(val) || $.trim(val) === "" ? 0 : parseFloat(val);
total += val;
});
$('.total_price').val(Math.round(total));
}
$(function() {
$(document).on('input', '.price', sumIt);
sumIt()
});
</script>
If I delete product row, the total price field is not updating the calculation. Suppose I added 4 rows, and give price value, after that I remove two rows, but the total price holds the previous 4 rows sum, it didn't update when I remove any row.
Here I want to show the total sum of product in total price.
And the Total Due calculation will be total due = (previous due + total price)- pay now
thanks

Laravel, javascript add rows table class select not working

I have this code which works fine. my problem is that when i go to add one or more rows in the table with the button
the select:
<select name = "product_id_product []" id = "product_id_product '. $ request-> count_product.'" class = "form-control js-select2" required>
it is as if it does not take the "js-select2" class
if instead I insert it manually in the index bypassing the whole class it works
I just can't figure out how to do it ..
index.blade:
<div class="card-body" style="text-align: center;">
<button type="button" name="aggiungi_prodotto" id="aggiungi_prodotto" class="btn btn-primary aggiungi_prodotto" style="visibility: visible;"><i class="mdi mdi-playlist-plus"></i>Aggiungi Prodotto</button>
<button type="button" name="aggiungi_accessorio" id="aggiungi_accessorio" class="btn btn-success aggiungi_accessorio" style="visibility: visible;"><i class="mdi mdi-playlist-plus"></i>Aggiungi Accessorio</button>
<button type="button" name="aggiungi_servizio" id="aggiungi_servizio" class="btn btn-warning aggiungi_servizio" style="visibility: visible;"><i class="mdi mdi-playlist-plus"></i>Aggiungi Servizio</button>
<button type="button" name="aggiungi_riga" id="aggiungi_riga" class="btn btn-danger aggiungi_riga" style="visibility: visible;"><i class="mdi mdi-playlist-plus"></i>Aggiungi Riga</button> <br/><br/><br/>
<div class="form-row">
<div class="table-responsive">
<table class="table table-hover ">
<thead>
<tr>
<th width="50%">Prodotto</th>
<th width="10%">Quantità</th>
<th width="10%">Acconto</th>
<th width="10%">Costo</th>
<th width="10%">Sconto TOT</th>
<th width="10%">Azioni</th>
</tr>
</thead>
<tbody id="prodottiRows">
</tbody>
</table>
</div>
</div>
<hr>
</div>
Javascript:
var count_prodotto = 0;
$(document).on('click', '#aggiungi_prodotto', function(){
count_prodotto = count_prodotto + 1;
var categorieID = document.getElementById('categorie_id').value;
var brandID = document.getElementById('brand_id').value;
var modelloID = document.getElementById('modello_id').value;
$.ajax({
type: 'POST',
url: "{{ route('autocomplete.fetch_prodotti') }}",
data: {
'_token': $('input[name=csrf-token]').val(),
'categorie_id':categorieID,
'brand_id':brandID,
'modello_id':modelloID,
'count_prodotto':count_prodotto
},
success:function(data){
$('#prodottiRows').append(data);
}
});
});
Controller:
public function fetch_prodotti(Request $request)
{
$products = Product::with('Multitenantable')
->where("stato_prodotto",'1')
->where("categorie_id",$request->categorie_id)
->where("brand_id",$request->brand_id)
->where("modello_id",$request->modello_id)
->pluck("nome_prodotto","id");
$prodotti = '
<tr id="row_prodotto'.$request->count_prodotto.'">
<td><select name="product_id_prodotto[]" id="product_id_prodotto'.$request->count_prodotto.'" class="form-control js-select2" required>
<option value="">Seleziona Prodotto</option>';
foreach ($products as $key => $product) {
$prodotti .= '<option value="'.$key.'">'.$product.'</option>';
# code...
}
$prodotti .='</select></td>
<td><input type="text" name="quantita_prodotto[]" id="quantita_prodotto'.$request->count_prodotto.'" class="form-control" value="0" required /></td>
<td><input type="text" name="acconto_prodotto[]" id="acconto_prodotto'.$request->count_prodotto.'" class="form-control" value="0" required /></td>
<td><input type="text" name="costo_prodotto[]" id="costo_prodotto'.$request->count_prodotto.'" class="form-control" value="0" required /></td>
<td><input type="text" name="sconto_prodotto[]" id="sconto_prodotto'.$request->count_prodotto.'" class="form-control" value="0" required /></td>
<td data-column="Rimuovi"><button type="button" name="remove_prodotto" id="'.$request->count_prodotto.'" class="btn btn-danger btn-xs remove_prodotto">Rimuovi</button></td>
</tr>';
return response()->json($prodotti);
}

Column cannot be null by using Auth

I'm inserting multiple data into the database. There is an error for my column report_by which is SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'report_by' cannot be null (SQL: insert into 'complaints' ('defect_id', 'image', 'description', 'report_by') values (1, C:\wamp64\tmp\php8E2E.tmp, leak, ?)) Inside column report_by should be the id of the user by using Auth. It's to tell that the complaint made by which users.
users table
id
role
email
typable_id
typable_type
complaints table
id
defect_id
image
description
report_by
ComplaintController.php
<?php
namespace App\Http\Controllers;
use Auth;
use App\Complaint;
use Illuminate\Http\Request;
class ComplaintController extends Controller
{
public function index()
{
return view('buyers.complaint');
}
public function create(Request $request)
{
if (count($request->defect_id) > 0) {
foreach($request->defect_id as $item=>$v) {
$data = array(
'defect_id' => $request->defect_id[$item],
'image' => $request->image[$item],
'description' => $request->description[$item],
'report_by' => $request->user_id,
);
Complaint::insert($data);
}
}
return redirect('/report-form')->with('success','Your report is submitted!');
}
}
complaint.blade.php
<div class="panel-heading">
<h3 class="panel-title"><strong>Make New Report</strong></h3>
</div>
<div class="panel-body">
<div>
<div class="panel">
<table class="table table-bordered">
<thead>
<tr>
<th><center>Type of Defect</center></th>
<th><center>Image</center></th>
<th><center>Description</center></th>
<th><center>Action</center></th>
</tr>
</thead>
<tbody>
<tr>
<td width="20%">
<form action="/report-create" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="text" class="hidden" id="user_id" value="{{Auth::user()->id}}">
<select class="form-control" name="defect_id[]">
<option value="" selected>Choose Defect</option>
#foreach(App\Defect::all() as $defect)
<option value="{{$defect->id}}">{{$defect->name}}</option>
#endforeach
</form>
</td>
<td width="15%">
<input type="file" class="form-control-file" name="image[]">
</td>
<td width="45%">
<input type="text" class="form-control" name="description[]">
</td>
<td width="10%">
<button type="button" class="btn btn-info btn-sm" id="add-btn"><i class="glyphicon glyphicon-plus"></i></button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<center><button type="submit" class="btn btn-primary">Submit</button></center>
</div>
Here my javascript inside the blade
#section('footer')
<script>
$(document).ready(function () {
$('#add-btn').on('click',function () {
var html = '';
html += '<tr>';
html += ' <td><input type="text" class="hidden" id="user_id" value="{{Auth::user()->id}}"><select class="form-control" name="defect_id[]"><option value="" selected>Choose Defect</option>#foreach(App\Defect::all() as $defect)<option value="{{$defect->id}}">{{$defect->name}}</option>#endforeach</td>';
html += ' <td><input type="file" class="form-control-file" name="image[]"></td>';
html += ' <td><input type="text" class="form-control" name="description[]"></td>';
html += ' <td><button type="button" class="btn btn-danger btn-sm" id="remove-btn"><i class="glyphicon glyphicon-minus"></i></button></td>';
html += '</tr>';
$('tbody').append(html);
})
});
$(document).on('click','#remove-btn',function () {
$(this).closest('tr').remove();
});
</script>
#stop

Javascript - Append row -dependent drop down list

I need a help to fix my dependent drop down list cloning problem. i have these three fields, 1.country_name,2.store_model,3.location_list, and on selecting country_name the store_model will populate and on selecting store_model the location lists will populate. this is working fine, but when i try to clone and append a row, the appended dropdown is not working properly. in the appended dropdown, the values are displaying based on the original dropdown selection.
this is my PHP page
<!-- BEGIN FORM-->
<form action="functions.php" method="post" enctype="multipart/form-data"
class="form-horizontal form_emp" id="form_sample_3" novalidate="novalidate">
<div class="form-body">
<input type="hidden" class="form-control" value="<?php echo $id;?>" name="id">
<input type="hidden" class="form-control" value="<?php echo $sp_id;?>" name="sp_id">
<input type="hidden" class="form-control tot_in" value="0" name="total_in">
<div class="row">
<div class="col-md-12">
<div class="table-scrollable">
<table class="table table-bordered edit-table">
<thead>
<tr>
<th width="10%"> # </th>
<th width="20%"> Country </th>
<th width="20%"> Store Model</th>
<th width="20%"> Loaction</th>
<th width="30%"> Update Comments </th>
</tr>
</thead>
<tbody id="items-row">
<?php
if(empty($userdata)):
?>
<tr class="item-row">
<td>
<a title="Remove row" href="javascript:;" class="dodelete delete btn red btn-outline">
<i class="fa fa-trash-o"></i></a></td>
<td class="form-group form-md-line-input">
<select multiple="multiple" class="form-control country_name" name="country_name[]">
<?php $q=mysql_query("SELECT `id`,`country_name` FROM `db_country` WHERE id in (select distinct country_id from db_locations where location_id in (select location_id from db_sp where sp_id=$sp_id)) ");
while($res=mysql_fetch_array($q)){
echo "<option ".(in_array($res['id'],$country_name)?"selected":"")." value='".$res['id']."'>".$res['country_name']."</option>";
}?>
</select>
</td>
<td class="form-group form-md-line-input">
<select multiple="multiple" class="form-control store_model" name="store_model[]">
<?php
$q=mysql_query("SELECT `id`,`store_model` FROM `db_store_model` WHERE id in (select distinct store_model_id from db_locations where location_id in (select location_id from db_sp where sp_id=$sp_id)) ");
while($res=mysql_fetch_array($q)){
echo "<option ".(in_array($res['id'],$store_model)?"selected":"")." value='".$res['id']."'>".$res['store_model']."</option>";
}?>
</select>
</td>
<td class="form-group form-md-line-input">
<select multiple="multiple" class="form-control location_list" name="location_list[]">
<?php
if(!empty($id)){
$q=mysql_query("SELECT `location_id`,`location_name` FROM `db_locations` WHERE location_id in (select location_id from db_sp where sp_id=$sp_id)");
while($res=mysql_fetch_array($q)){
echo "<option ".(in_array($res['location_id'],$location_list)?"selected":"")." value='".$res['location_id']."'>".$res['location_name']."</option>";
}}?>
</select>
<div class="form-control-focus loading"> </div>
</td>
<td align="centre" class="form-group form-md-line-input">
<input type="text" class="form-control" name="comments[]"></td>
</tr>
<?php
else:
$count=count($sp_detail);
for($i=0; $i<$count;$i++){
?>
<tr class="item-row">
<a title="Remove row" href="javascript:;" class="dodelete delete btn red btn-outline">
<i class="fa fa-trash-o"></i></a></td>
<td class="form-group form-md-line-input">
<select multiple="multiple" class="form-control country_name" name="country_name[]">
<option value="">Select Any</option>
<?php foreach($country_name as $key=>$cname){ ?>
<option value="<?php echo $key ;?>" <?php echo ($sp_detail[$i]['country_name']==$key?"selected":"");?>><?php echo $cname ;?></option>
<?php }?>
</select>
</td>
<td class="form-group form-md-line-input">
<select multiple="multiple" class="form-control store_model" name="store_model[]">
<option value="">Select Any</option>
<?php foreach($store_model as $key=>$smodel){ ?>
<option value="<?php echo $key ;?>" <?php echo ($sp_detail[$i]['store_model']==$key?"selected":"");?>><?php echo $smodel ;?></option>
<?php }?>
<div class="form-control-focus loading"> </div>
</td>
<td class="form-group form-md-line-input">
<select multiple="multiple" class="form-control location_list" name="location_list[]">
<option value="">Select Any</option>
<?php foreach($location_list as $key=>$loclist){ ?>
<option value="<?php echo $key ;?>" <?php echo ($sp_detail[$i]['location_list']==$key?"selected":"");?>><?php echo $loclist ;?></option>
<?php }?>
</select>
<div class="form-control-focus loading"> </div>
</td>
</tr>
<?php
}
endif;
?>
</tbody>
</table>
</div>
</div>
</div>
<div class="row">
<div class="col-md-2">
<a title="Add a row" href="javascript:;" class="addrow btn blue btn-outline">Add a row</a>
</div>
<div class="col-md-8 invoice-block text-right">
<div class="form-group form-md-line-input">
<label class="col-md-3 control-label" for="form_control_1">Update Type
<span class="required">*</span>
</label>
<div class="col-md-6">
<select class="form-control" name="event_status">
<option value="1">Update</option>
</select>
<div class="form-control-focus"> </div>
</div>
</div>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-6">
<button type="submit" name="action" value="update_event" class="btn green">Submit</button>
<button type="reset" class="btn default reset">Reset</button>
</div>
</div>
</div>
</form>
<!-- END FORM-->
this is my functions.php
if(isset($_POST['action'])&& $_POST['action']=='selectUpdate'){
$post=$_POST;
$country_id=json_encode($post['country_name']);
$country_ids=join(',',$post['country_name']);
$sp_id=$post['sp_id'];
$store_model_id=json_encode($post['store_model']);
$store_model_ids=join(',',$post['store_model']);
$q=mysql_query("SELECT `location_id`,`location_name` FROM `db_locations` WHERE country_id in ($country_ids) and store_model_id in ($store_model_ids) and location_id in (select location_id from db_sp where sp_id=$sp_id)order by country_id,store_model_id");
$qno=mysql_num_rows($q);
if($qno>0){
while($res=mysql_fetch_array($q)){
echo "<option value='".$res['location_id']."'>".$res['location_name']."</option>";
}
}
else{
echo "<option value=''>No Data</option>";
}
}
this is my JavaScript
<script>
$(document).ready(function(){
$(document).on('click','.dodelete',function(){
if($('.edit-table #items-row').find('tr').length > 1) { $(this).parents('tr').remove(); }
else{alert('All rows cant be deleted');}
});
var setSelectsEvents = function(rowElement) {
$(rowElement).on('change', '.country_name,.store_model', function(){
var store_model=$(rowElement).find('.store_model')[0].value;
var country_name=$(rowElement).find('.country_name')[0].value;
var sp_id=<?php echo $sp_id ?>;
//var store_model=$(this).val();
$('.loading').html('<img src="layouts/layout/img/loading.gif"/>');
$.ajax({
type: 'post',
url: 'functions.php',
data: {
sp_id:<?php echo $sp_id ?>,store_model:store_model,country_name:country_name, action:"selectUpdate",
},
success: function (res) {
$('.loading').html("");
$($(rowElement).find('.location_list')[0]).html(res);
$('#my_multi_select1').multiSelect();
}
});
});
};
setSelectsEvents('.item-row');
$('.addrow').click(function(){
var elem = $('#items-row').find('tr:first').clone();
var appendedRow = $('#items-row').append(elem).children(':last-child');
setSelectsEvents(appendedRow);
});
$(document).on('click','.reset',function(){
emptyTable();
});
});
$(function(){
$('.datepicker').datepicker({
format: 'yyyy-mm-dd',
startDate: 'dateToday',
//startDate: '+15d',
autoclose: true
});
});
im not good at JavaScript, somewhere i am making mistake. please help.
I think it has some event handler like $('select.coutry_name').on('change', ...
But these event handlers are not set cloned rows selects.
So it will work fine selects event handler part and $('.addrow').click change to like following.
// **UPDATED JavaScript**
<script>
$(document).ready(function(){
$(document).on('click','.dodelete',function(){
if($('.edit-table #items-row').find('tr').length > 1) { $(this).parents('tr').remove(); }
else{alert('All rows cant be deleted');}
});
var setSelectsEvents = function(rowElement) {
$(rowElement).on('change', '.country_name,.store_model', function(){
var store_model=$($(rowElement).find('.store_model')[0]).val();
var country_name=$($(rowElement).find('.country_name')[0]).val();
var sp_id=<?php echo $sp_id ?>;
//var store_model=$(this).val();
$('.loading').html('<img src="layouts/layout/img/loading.gif"/>');
var data = {
sp_id:1,store_model:store_model,country_name:country_name, action:"selectUpdate",
};
$('.loading').html('<img src="/images/loading.gif"/>');
$.ajax({
type: 'post',
url: 'functions.php',
data: JSON.stringify(data),
contentType: 'application/JSON',
dataType : 'JSON',
success: function (res) {
$('.loading').html("");
$($(rowElement).find('.location_list')[0]).html(res);
$('#my_multi_select1').multiSelect();
}
});
});
};
setSelectsEvents('.item-row');
$('.addrow').click(function(){
var elem = $('#items-row').find('tr:first').clone();
var appendedRow = $('#items-row').append(elem).children(':last-child');
setSelectsEvents(appendedRow);
});
$(document).on('click','.reset',function(){
emptyTable();
});
});
$(function(){
$('.datepicker').datepicker({
format: 'yyyy-mm-dd',
startDate: 'dateToday',
//startDate: '+15d',
autoclose: true
});
});
</script>
It is posted data in JSON, has to decode JSON data on PHP.
if(isset($_POST['action'])&& $_POST['action']=='selectUpdate'){
$post=json_decode($_POST, true);
//$country_id=json_encode($post['country_name']); //not used
$country_ids=is_array($post['country_name']) ? join(',',$post['country_name']) : $post['country_name'];
$sp_id=$post['sp_id'];
//$store_model_id=json_encode($post['store_model']); //not used
$store_model_ids=is_array($post['store_model']) ? join(',',$post['store_model']) : $post['store_model'];
$q=mysql_query("SELECT `location_id`,`location_name` FROM `db_locations` WHERE country_id in ($country_ids) and store_model_id in ($store_model_ids) and location_id in (select location_id from db_sp where sp_id=$sp_id)order by country_id,store_model_id");
$qno=mysql_num_rows($q);
if($qno>0){
while($res=mysql_fetch_array($q)){
echo "<option value='".$res['location_id']."'>".$res['location_name']."</option>";
}
}
else{
echo "<option value=''>No Data</option>";
}
}

Categories

Resources