Validation error for multiple input field Laravel 8 - javascript

I have a validation problem regarding multiple input fieldL to store in the database. When I submit, the errors show "additional mark field is required." I try to test dd($request) but the attributes is null. How can I store in DB with multiple input fields?
Controller
public function StoreAdditionalProcuments(Request $request)
{
$request->validate([
'additional_remark' => 'required',
]);
foreach ($request->addmore as $key => $value) {
$input = $request->all();
$input['additional_remark'] = $value['additional_remark'];
AssetProcument::create($input);
}
return redirect('asset')->with('success', 'Maklumat Aset berjaya disimpan.');
}
AssetProcument.php Model
class AssetProcument extends Model
{
public $fillable = [
'additional_remark',
];
Blade
<form action="{{ route('asset_store_additional_procument') }}" method="POST">
#csrf
<div class="card-body">
<div class="col">
<table class="table table-bordered" id="dynamicTable">
<thead>
<tr>
<th>Catatan</th>
</tr>
</thead>
<tbody>
<tr>
<td style="width:50%"><textarea type="text" name="addmore[][additional_remark]"
class="form-control"></textarea></td>
<td>
<button type="button" name="add" id="add" class="btn btn-success">Tambah</button>
</td>
</tr>
</body>
</table>
</div>
<div class="col-12">
<input type="submit" value="Save Changes" class="btn btn-success float-right">
</div>
</div>
</form>
<script type="text/javascript">
var i = 0;
$("#add").click(function(){
++i;
$("#dynamicTable").append('<tr><td><textarea type="text" name="addmore['+i+'][additional_remark]" class="form-control" /></textarea></td>'.'
<td><button type="button" class="btn btn-danger remove-tr">Remove</button></td></tr>');
});
$(document).on('click', '.remove-tr', function(){
$(this).parents('tr').remove();
});
Route
Route::post('asset_store_additionalprocuments',[AssetController::class,'StoreAdditionalProcuments'])->name('asset_store_additional_procument');

Since additional_remark input is addmore[][additional_remark], your validation should be like this
$request->validate([
'addmore.*.additional_remark' => 'required',
]);
* mark is all indexes of addmore array

Related

Unable to edit data on the same view page laravel

I want to update the business hour on the same page. There are other answer that I review in the stackoverflow but I still cannot manage. Help really appreciated.
Model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Hour extends Model
{
public $table = 'biz_hour';
protected $primaryKey = 'day_id';
protected $fillable = [
'day_id', 'day_name', 'start_time', 'end_time', 'day_off'
];
public $timestamps = false;
}
Controller
public function update(Request $request, Hour $biz_hour)
{
$request->validate([
'start_time' => 'required',
]);
$start_time = \App\Models\Hour::find($biz_hour);
['start_time' => $request->start_time];
foreach($biz_hour as $biz_hour){
$start_time->save();
}
return redirect('start_time');
//$biz_hour->update($request->all());
//return redirect()->route('biz_hour.index');
}
Biz_hour.blade.php
<div class="table-responsive">
<table class="table">
<thead class="text-uppercase">
<tr>
<th scope="col">Day</th>
<th scope="col">Start Time</th>
<th scope="col">End Time</th>
<th scope="col">is Day off?</th>
</tr>
</thead>
#foreach($biz_hour as $biz_hour)
<form action="{{ route('biz_hour.update',$biz_hour->day_id) }}" method="POST">
#csrf
#method('PUT')
<tbody>
<tr>
<th scope="row"><br>{{$biz_hour->day_name}}</th>
<td><div class="form-group">
<input class="form-control" type="time" value={{ Carbon::parse($biz_hour->start_time)->format('h:i') }} name="start_time"></div>
</td>
<td><div class="form-group">
<input class="form-control" type="time" value={{$biz_hour->end_time}} name="end_time"></div>
</td>
<td><br><label class="switch">
<input type="checkbox">
<span class="slider round"></span>
</label></td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
<div class="main-content-inner">
<div class="col-lg-6 mt-5">
<button type="submit" class="btn btn-primary mb-3" name="upload">Save</button>
</div>
</div>
</form>
After clicking save button, the page only refresh but the data is not sent to the database. Thanks in advance.
Update is not done because you actually didn't assign the new start_time for the start_time you wanted to update.
Try this
public function update(Request $request, Hour $biz_hour)
{
$request->validate([
'start_time' => 'required',
]);
$start_time = \App\Models\Hour::find($biz_hour);
$start_time->start_time => $request->start_time;
foreach($biz_hour as $biz_hour){
$start_time->save();
}
return redirect()->back()->with('status', 'updated');
}

Insert Multiple Data into Database with Laravel

I'm trying to insert multiple data into my database by using array and javascript. But what happened is, I only could submit one data into my complaints table. The balanced is not inserted. There is no error appeared.
users table
id
role
email
typable_id
typable_type
buyers table
id
name
buyer_id
address
phone_no
defects table
id
name
complaints table
id
defect_id
image
description
report_by
ComplaintController.php
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' => auth()->user()->typable->buyer_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() }}
<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>
javascript in blade
<script>
$(document).ready(function () {
$('#add-btn').on('click',function () {
var html = '';
html += '<tr>';
html += '<td><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>

How to clear values of dropdownlists in angularjs

I am using ng-repeat in HTML to loop on a javascript array. showing this array in select.
what i want to do is to clear all selected data from these dropdownlists when press on a button
HTML
<div class="widget-title">
<div class="widget-controls">
<button class="btn btn-xs btn-primary" ng-click="newassignment()">New</button>
<button class="btn btn-xs btn-success" ng-click="saveavd()">Save</button>
</div>
<h3><i class="icon-ok-sign"></i>Assignment</h3>
</div>
<div id="vacation" class="widget-content" style="height:81vh; overflow:auto;">
<div class="row">
<table style="width: 70%;" border="1">
<thead>
<tr>
<th>Departments</th>
<th>Work Level</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="d in departments | filter : depts">
<td>
<input style=" margin-top: 0;" type="checkbox" ng-model="d.details"/> {{d.Dep_LDesc}}
</td>
<td>
<select class="form-control input-sm" ng-model="wrklevel2">
<option ng-repeat="w in worklevel" value="{{w.lvlid}}">{{w.lvlnm}}</option>
</select>
</td>
</tr>
</tbody>
</table>
angularjs
$scope.worklevel = [
{ lvlid: 1, lvlnm: 'First Level' },
{ lvlid: 2, lvlnm: 'Second Level' }
]
$scope.newassignment = function () {
$scope.wrklevel2 = {};
angular.forEach($scope.departments, function (d) {
d.details = false;
})
}
You should have different models for your selects inside your ng-repeat to achieve that you can try the following
(ng-model="d.wrklevel2")
<select class="form-control input-sm" ng-model="d.wrklevel2">
<option ng-repeat="w in worklevel" value="{{w.lvlid}}">{{w.lvlnm}}</option>
</select>
after that you can also clear values of select inside your forEach loop
angular.forEach($scope.departments, function (d) {
d.details = false;
d.wrklevel2 = undefined;
})
set the ngModel of select to empty string -
function saveavd()
{
$scope.wrklevel2 = ""
// ...
}

Ajax not working on multiple inserts - CI

I want to save multiple data in one go using codeigniter and then on success load the data on my datatable wihtout refreshing the whole page. I am able to do this successfully if I use modal and insert a single value but when I try to save multiple values, it doesn't work. I produce my input boxes on button click. Below are my codes:
CONTROLLER
public function add_multiple_orders(){
$dataset=[];
$item_name=$this->input->post('m_item_name');
$quantity=$this->input->post('m_quantity');
$amount=$this->input->post('m_amount');
$order_comment=$this->input->post('m_order_comment');
$branch_name=$this->input->post('m_branch_name');
$date_added=$this->input->post('m_date_added');
for($i=0;$i<sizeof($item_name);$i++){
$dataset[$i]=array(
'date_added'=>$date_added,
'item_name'=>$item_name[$i],
'quantity'=>$quantity[$i],
'amount'=>$amount[$i],
'ordered_by'=>$this->session->userdata['username'],
'order_status'=>'ordered',
'order_comment'=>$order_comment[$i],
'branch_name'=>$branch_name
);
}
$result=$this->sales_model->insert_mult_orders($dataset);
}
VIEW
<a name="mult_page">
<button class="btn btn-info" data-toggle="collapse" data-target="#add_multiple" style="margin-left: 20px;">Add Multiple Orders</button>
<div class="collapse" id="add_multiple" style="width: 95%; margin: 0 auto; margin-top: 10px;">
<div class="row">
<div class="col-md-12">
<div class="panel panel-primary">
<div class="panel-heading">
</div>
<div class="panel-body">
<form class="form_mult_ordrs form-inline" method="post">
<div class="form-group">
<label for="m_date_added">Date</label>
<input type="date" name="m_date_added" required>
</div>
<div class="form-group">
<label for="m_branch_name" class="control-label">Branch Name</label>
<select name="m_branch_name" class="form-control">
<option value="superdome">Superdome</option>';
<option value="seaside">Sea Side</option>
<option value="robinsons">Robinsons</option>
</select>
</div>
<div class="btn btn-warning pull-right" onclick="add_new_row()">Add more</div>
<hr>
<div style="font-weight: bold;">Total Php <input type="text" id="total_result" placeholder="0.00" class="form-control"></div>
<br>
<table id="mult_ord_tbl" class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th class="ui-help-center">Item Name</th>
<th class="ui-help-center">Quantity</th>
<th class="ui-help-center">Amount</th>
<th class="ui-help-center">Comment</th>
<th class="ui-help-center">Delete</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select name="item_name[]" class="form-control">
<?php foreach($items as $item){
echo '<option value"='.$item->item_name.'">'.$item->item_name.'</option>';
} ?>
</select>
</td>
<td><input type="text" name="m_quantity[]" placeholder="Quantity"></td>
<td><input type="text" name="m_amount[]" id='m_amount[]' placeholder="Amount" onblur="total_values()"></td>
<td><input type="text" name="m_order_comment[]" placeholder="Commment"></td>
<td>
<button class="btn btn-danger" onclick="delete_row(this)"><i class="glyphicon glyphicon-remove"></i></button>
</td>
</tr>
</tbody>
</table>
<tr>
<td colspan="12">
<button id="btn_mult_ordrs" class="btn btn-success" onclick="save_mult_ordrs()" value="">Submit All</button>
</td>
</tr>
</form>
</div> <!-- end of panel body -->
<div class="panel-footer">
footer
</div>
</div> <!-- end of panel primary -->
</div> <!-- end of column 12 -->
</div> <!-- end of row -->
</div> <!-- end of collapse -->
<script type="text/javascript">
$(document).ready(function(){
$('#table_id').DataTable({
"order":[[0,"desc"]]
});
});
function save_mult_ordrs(){
if(confirm("Are you done?")){
var url="<?php echo site_url('sales/add_multiple_orders')?>";
add_new_row();
// $("#form_mult_ordrs").submit();
$.ajax({
url:url,
type:"POST",
data:$('#form_mult_ordrs').serialize(),
datatype:"JSON",
success:function(data)
{
alert('All data has been saved.');
location.reload();
},
error:function(jqXHR, textStatus, errorThrown){
alert('Error in saving.');
}
});
}
}
function add_new_row(){
var arrTables = document.getElementById('mult_ord_tbl');
var oRows = arrTables.rows;
var numRows = oRows.length;
var newRow = document.getElementById('mult_ord_tbl').insertRow( numRows );
var cell1=newRow.insertCell(0);
var cell2=newRow.insertCell(1);
var cell3=newRow.insertCell(2);
var cell4=newRow.insertCell(3);
var cell5=newRow.insertCell(4);
cell1.innerHTML = "<tr><td><select name='m_item_name[]' class='form-control'>" +
<?php
foreach($items as $item){
echo ('"<option value=\"'.$item->item_name.'\">'.$item->item_name.'</option>"+');
}
?>
+ "</select></td>";
cell2.innerHTML="<td height='5'><input type='text' name='m_quantity[]' placeholder='Quantity'></td>";
cell3.innerHTML="<td height='5'><input type='text' name='m_amount[]' placeholder='Amount' onblur='total_values()'></td>"
cell4.innerHTML="<td height='5'><input type='text' name='m_order_comment[]' placeholder='Comment'></td>";
cell5.innerHTML="<td><button class='btn btn-danger' onclick='delete_row(this)''><i class='glyphicon glyphicon-remove'></i></button></td></tr>";
}
</script>
MODEL
public function insert_mult_orders($data){
$this->db->insert_batch('piercapitan.sls_ordrs',$data);
return $this->db->affected_rows();
}
Your help is immensely appreciated.
Never mind guys. I found what's wrong. It's my form id! I somehow placed the name on the class and not on the id.
<form class="form_mult_ordrs form-inline" method="post">
It should have been:
<form id="form_mult_ordrs" class="form-inline" method="post">

Form is presenting same data in php while loop

I am trying to get an edit form to work with the loop in the php. I have a delete button and it works just fine. The edit form keeps presenting only the first row in the table. In firebug, it shows that all the other forms are there with the correct unique id for each but only the first form shows when edit is clicked on different rows. Can someone help me as to why?
<table id="table_id" class="table table-hover table-striped">
<thead>
<tr>
<th>ID #</th>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_assoc($search_sql)) {
?>
<tr>
<td id = "clicked"><?=$row['ID']?></td>
<td id = "clicked"><?=$row['Product']?></td>
<td id = "clicked"><?=$row['Quantity']?></td>
<td id = "clicked">$ <?=$row['Price']?></td>
<td>
<button class="btn btn-warning btn-sm" onclick="div_show2(this, '<?=$row['ID']?>'); return false;"><span class="glyphicon glyphicon-edit"></span>Edit</button>
<!-- Modal for the Edit Data Form -->
<div id ="hidden-form2">
<div id = "popupContact">
<form action= "updateData.php" id = "editForm<?=$row['ID']?>" method="POST" name="editForm">
<input type="hidden" name="ID" value="<?=$row['ID']?>">
<div class="form-group">
<label for="product">Product</label>
<input type="text" class="form-control" id="product<?=$row['ID']?>" name="product" value="<?=$row['Product']?>">
</div>
<div class="form-group">
<label for="quantity">Quantity</label>
<input type="text" class="form-control" id="quantity<?=$row['ID']?>" name="quantity" value="<?=$row['Quantity']?>">
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="text" class="form-control" id="price<?=$row['ID']?>" name="price" value="<?=$row['Price']?>">
</div>
<button type="button" class="btn btn-default" onclick="formHide2()">Close</button>
<button type="submit" id="save" class="btn btn-primary">Save changes</button>
</form>
</div>
</div>
<!--End of Edit Form-->
</td>
<td>
<!--Delete Button Form-->
<form method="post" action="deleteData.php">
<button class="btn btn-danger btn-sm" type="submit"><span class="glyphicon glyphicon-trash"></span>Delete</button>
<input type="hidden" id="ID" name="ID" value="<?=$row['ID']?>">
</form>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
//script for calling the edit forms as a modal popup
//Function To Display Popup for Edit form
function div_show2() {
document.getElementById("editForm").reset();
document.getElementById('hidden-form2').style.display = "block";
}
//Function to Hide Popup
function formHide2(){
document.getElementById('hidden-form2').style.display = "none";
}
Your show_div2 function is only showing one element.
document.getElementById('hidden-form2').style.display = "block";
That shows you why you are only seeing the first row.
Update your HTML and Javascript as follows
HTML
<div id="hidden-form2<?=$row['ID']?>">
Javascript
function div_show2(id) {
document.getElementById("editForm"+id).reset();
document.getElementById('hidden-form2'+id).style.display = "block";
}
To avoid having any problems like this in the future, always make sure that your id's are unique.
The first 4 td I see all use the same id name clicked. Try to fix that first and see what happens.
<td class="clicked" id="clickedID<?=$row['ID']?>"><?=$row['ID']?></td>
<td class="clicked" id="clickedProduct<?=$row['ID']?>"><?=$row['Product']?></td>
<td class="clicked" id="clickedQuantity<?=$row['ID']?>"><?=$row['Quantity']?></td>
<td class="clicked" id="clickedPrice<?=$row['ID']?>">$ <?=$row['Price']?></td>

Categories