How to ignore sync if value is null in laravel - javascript

I have a form where I will sync my attributes (it's like tags) but the issue is I get error while select or even not select any attribute.
Here is the error I get:
SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '' for
column 'attribute_id' at row 1 (SQL: insert into product_attributes
(attribute_id, product_id) values (*parameters, 65))
Before codes I need to explain what I try to do:
Select my attributes while creating new post
Give value to selected attribute
save product_id arribute_id and attribute_value in product_attributes table.
Here is my blade:
$(function() {
$('a.pl').click(function(e) {
e.preventDefault();
$('#phone').append('<div class="col-md-6"><select class="tagsselector mb-20 form-control" name="attribute[]"><option value="{{ $attribute->id }}">{{ $attribute->title }}</option></select></div><div class="col-md-6"><input name="attribute_value" class="form-control" type="text" placeholder="Value"></div>');
});
$('a.mi').click(function (e) {
e.preventDefault();
if ($('#phone input').length > 1) {
$('#phone').children().last().remove();
}
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="RegSpLeft" id="phone" style="margin-top:30px;">
<div class="col-md-6">
<label for="attributes" hidden>Attributes</label>
<select class="mb-20 form-control" name="attributes[]">
<option value="" selected>Select Attributes</option>
#foreach($attributes as $attribute)
<option value="{{ $attribute->id }}">{{ $attribute->title }}</option>
#endforeach
</select>
</div>
<div class="col-md-6">
<label for="attribute_value" hidden>attribute value</label>
<input name="attribute_value" class="form-control" type="text" placeholder="Value">
</div>
</div>
<div class="RegSpRight">
+
-
</div>
Here is my controller:
public function create()
{
$categories = Category::all();
$subcategories = Subcategory::all();
$attributes = Attribute::all();
if (is_null($attributes)) {
$attributes = [];
}
$user = Auth::user();
return view('admin.products.create', compact('user', 'categories', 'subcategories', 'attributes'));
}
My Product model:
public function attributes()
{
return $this->belongsToMany(Attribute::class, 'product_attributes', 'product_id', 'attribute_id');
}
My Attribute model:
public function products(){
return $this->belongsToMany(Product::class);
}

Related

How to pass a list from controller post action to a view without using Json?

I'm coding with ASP.NET Core. I have a form in a view that has several select inputs to insert orders. I want to change asp-items in select input of Products at run time, after changing select inputs of Properties of Products.
In other words, a select input populates with a new list, after selecting new value in other inputs.
I try to use ajax for bind new list to select. but I don't know how to send the output list to ajax without json result. Is there any way to send list to view?
View's Code:
<form id="InsertForm">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="ProductTitleId" class="control-label"></label>
<select asp-for="ProductTitleId" asp-items="#ViewBag.ProductTitles" class="form-control" id="txtProductTitleId" name="SearchItem">
<option value="0" disabled selected>Select an item...</option>
</select>
<span asp-validation-for="ProductTitleId" class="text-danger </span>
</div>
<div class="form-group">
<label asp-for="ProductTypeId" class="control-label"></label>
<select asp-for="ProductTypeId" asp-items="#ViewBag.ProductTypes" class="form-control" id="txtProductTypeId" name="SearchItem">
<option value="0" disabled selected>Select an item...</option>
</select>
<span asp-validation-for="ProductTypeId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="SizeId" class="control-label"></label>
<select asp-for="SizeId" asp-items="#ViewBag.Sizes" id="txtSizeId" class="form-control" name="SearchItem">
<option value="0" disabled selected>Select an item...</option>
</select>
<span asp-validation-for="SizeId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="FinalProductId" class="control-label"></label>
<select asp-for="FinalProductId" asp-items="#ViewBag.FinalProducts" class="form-control" dir="rtl" id="txtFinalProductId">
<option value="0" disabled selected>Select an item...</option>
</select>
<span asp-validation-for="FinalProductId" class="text-danger"></span>
</div>
<div class="form-group">
<button type="submit" class="btn">Insert</button>
</div>
</form>
<script>
$(document).ready(function () {
$('[name = SearchItem]').change(function () {
var _url = '#Url.Action("FindFinalProductCode", "Order")';
$.ajax({
url: _url,
type: "Post",
data: {
ProductTitleId: $("#txtProductTitleId option:selected").val(),
ProductTypeId: $("#txtProductTypeId option:selected").val(),
SizeId: $("#txtSizeId option:selected").val(),
},
success: function (data) {
$("#txtFinalProductId").empty();
$("#txtFinalProductId").append('<option value="' + "0" + '">' + "Select an item..." + '</option>');
$("#txtFinalProductId").items(data); ///????
});
},
error: function (data) {
alert(data);
}
});
});
});
</script>
Controller's Code: OrderController.cs
[HttpPost]
public IActionResult FindFinalProductCode(FinalProductViewModel finalProductViewModel)
{
List<FinalProduct> finalProducts = FindFinalProduct(finalProductViewModel);
return OK(finalProducts);
}
ViewModel's Code: FinalProductViewModel.cs
public class FinalProductViewModel
{
[Display(Name = "Title")]
public int ProductTitleId { get; set; }
[Display(Name = "Type")]
public int ProductTypeId { get; set; }
[Display(Name = "Size")]
public int SizeId { get; set; }
}
I don't know how to re-populate asp-items with ajax at run time.
How to change my code to run correctly?

Search by Name Category/SubCategory using Javascript on laravel view

I had some problems with the task. I'm not very good with javascript. Please help.
I display categories as form and I want to when the form to be typed to display products that are set for each category and sub-category. In the next task I have to make sure that when the form is typed, the categories show up and, also without refreshing the page.
code on product_upload.blade.view
<div class="form-group row" id="category">
<label class="col-md-3 col-from-label">{{translate('Category')}}</label>
<div class="col-md-8">
<select class="form-control aiz-selectpicker" name="category_id" id="category_id" data-live-search="true" required>
#foreach($categories as $category)
<option value="{{$category->id}}">{{ $category->getTranslation('name') }}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group row" id="subcategory">
<label class="col-md-3 col-from-label">{{translate('Subcategory')}}</label>
<div class="col-md-8">
<select class="form-control aiz-selectpicker" name="subcategory_id" id="subcategory_id" data-live-search="true" required>
</select>
</div>
</div>
My script :
function get_subcategories_by_category(){
var category_id = $('#category_id').val();
$.post('{{ route('subcategories.get_subcategories_by_category') }}',{_token:'{{ csrf_token() }}', category_id:category_id}, function(data){
$('#subcategory_id').html(null);
for (var i = 0; i < data.length; i++) {
$('#subcategory_id').append($('<option>', {
value: data[i].id,
text: data[i].name
}));
$(".aiz-selectpicker").selectpicker();
}
get_subsubcategories_by_subcategory();
});
}
$('#category_id').on('change', function() {
get_subcategories_by_category();
});
$('#subcategory_id').on('change', function() {
get_subsubcategories_by_subcategory();
});
and my controller :
public function get_subcategories_by_category(Request $request)
{
$subcategories = SubCategory::where('category_id', $request->category_id)->get();
return $subcategories;
}
But that wont work.

score validation behaves abnormally in Laravel

In my Laravel-5.8 application I have this code:
public function findScore(Request $request)
{
$userCompany = Auth::user()->company_id;
$userEmployee = Auth::user()->employee_id;
$identities = DB::table('identity')->select('id')->where('company_id', $userCompany)->where('is_current', 1)->first()->id;
$weightedscore = 0;
$weightedscore = DB::table('goals')->select(DB::raw("IFNULL(SUM(weighted_score),0) as weighted_score"))->where('identity_id', $identities)->where('employee_id', $userEmployee)->where('parent_id', $parentid)->whereNull('deleted_at')->first();
$weightedscorex = 0;
$maxscore = DB::table('goal_types')->select('max_score')->find($child->parent_id);
return response()->json([
'maxscore' => $maxscore->max_score,
'weightedscore' => $weightedscore->weighted_score,
]);
}
Route:
Route::get('get/findScore','GoalsController#findScore')->name('get.scores.all');
view (create.blade.php)
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Goal Type:<span style="color:red;">*</span></label>
<select id="goal_type" class="form-control #error('goal_type_id') is-invalid #enderror" name="goal_type_id">
<option value="">Select Goal Type</option>
#foreach ($categories as $category)
#unless($category->name === 'Job Fundamentals')
<option hidden value="{{ $category->id }}" {{ $category->id == old('goal_type_id') ? 'selected' : '' }}>{{ $category->name }}</option>
#if ($category->children)
#foreach ($category->children as $child)
#unless($child->name === 'Job Fundamentals')
<option value="{{ $child->id }}" {{ $child->id == old('goal_type_id') ? 'selected' : '' }}> {{ $child->name }}</option>
#endunless
#endforeach
#endif
#endunless
#endforeach
</select>
<input type="hidden" id="max_score" class="form-control" >
<input type="hidden" id="weighted_score" value="0" class="form-control" >
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Weight(%):<span style="color:red;">*</span></label>
<input type="text" name="weighted_score" id="total_weighted_score" value="{{ old('weighted_score', $goal->weighted_score) }}" placeholder="Enter weighted score here" class="form-control #error('weighted_score') is-invalid #enderror" max="120" onkeyup="checkScore(this.value)">
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-primary">Save</button>
</div>
Javascript
<script type="text/javascript">
$(document).ready(function() {
$(document).on('change', '#goal_type', function() {
var air_id = $(this).val();
var a = $(this).parent();
var op = "";
$.ajax({
type: 'get',
url: '{{ route('get.scores.all') }}',
data: { 'id': air_id },
dataType: 'json', //return data will be json
success: function(data) {
console.log(data.maxscore);
console.log(data.weightedscore);
$('#max_score').val(data.maxscore);
$('#weighted_score').val(data.weightedscore);
},
error:function(){
}
});
});
});
</script>
<script type="text/javascript">
function checkScore(value){
let max_score = $("#max_score").val();
let weighted_score = $("#weighted_score").val();
let sumValue = parseInt(weighted_score) + parseInt(value);
if (sumValue > max_score) {
alert("sum value is greater than max score");
$("#total_weighted_score").val('');
return false;
}
}
</script>
On select dropdown change using id="goal_type", I loaded the max_score of the selected goal type.
onkeyup="checkScore(this.value)" is used to validated if the accumulated weighted score is greater than max_score. If yes, then it raises an alert:
alert("sum value is greater than max score");
This works very well in most of the cases. However, I found out that the validation is unstable. At times it doesn't work. It raises the alert even when the accumulated weighted score is less than max_score
The issue happens at various scenarios. But at times when a user tries to enter value into the text input without selecting the dropdown.
How do I resolve this?
This isn't necessarily an optimal solution, but should solve your problem. If the ajax has not returned your values yet just initialize them in a way that they wont trigger your error.
function checkScore(value) {
let max_score = $("#max_score").val();
max_score = max_score ? parseInt(max_score) : Number.MAX_SAFE_INTEGER;
let weighted_score = $("#weighted_score").val();
weighted_score = weighted_score ? parseInt(weighted_score) : 0;
let sumValue = weighted_score + parseInt(value);
if (sumValue > max_score) {
alert("sum value is greater than max score");
$("#total_weighted_score").val('');
return false;
}
}

Passing my select id to route controller and show to another blade file

I'm trying to pass the selected id to controller using a route. But nothing happen shown at another blade file. Here, is my code
my blade contain that script
$("#state").on("change", function() {
var id = $(this).val();
console.log(id)
var cuid = document.getElementById("cu").value;
console.log(cuid)
});
state select
<div class="col-md-12 form-group" id="stateBranch">
<label for="sm" class="control-label">{{ __('messages.state') }}</label>
<select name="state" id="state" class="input-sm form-control">
<option value="">{{ __('messages.select') }}</option>
#if(!empty(request()->session()->get('stateList')))
#foreach(request()->session()->get('stateList') as $state)
<option value="{{ $state->st_state_code }}">{{ $state->st_state_desc }}</option>
#endforeach
#endif
</select>
</div>
cu select
<div class="col-md-12 form-group" id="custbranchreport">
<label for="sm" class="control-label">{{ __('messages.module.customer') }}<span class="compulsory"> * </span></label>
<select name="cu" id="cu" class="input-sm form-control" onchange="">
<option value="">{{ __('messages.select') }}</option>
#if(!empty($custList))
#foreach($custList as $cu)
<option value="{{ $cu->cu_customer_ID }}">{{ $cu->cu_customer_Shortname }}-{{ $cu->cu_customer_Name }}</option>
#endforeach
#endif
</select>
<input id="hid" type="hidden" name="hid" value=""/>
</div>
open new window route via onclick
<a class="btn btn-sm btn-default pull-right" type="button" title="Search Branch" onclick="openNewWindow('{{ route('reporting.branchCheckBoxList', ['cu' ,'state']) }}')" ><i class="fa fa-hand-o-up"></i> Choose Branch</a>
routes/web.php
Route::get('reporting/branchCheckBoxList/{cuid}/{stid?}','GenReportController#branchCheckBoxList')->name('reporting.branchCheckBoxList');
Controller
public function branchCheckBoxList(Request $request) {
$cuid = $request->get('cuid');
$stid = $request->get('stid');
return view('report.BranchCheckBoxList', compact('cuid','stid'));
}
You cannot used request in your method arguments considering that you are using a get request in your route, to access those parameters change your controller to this.
public function branchCheckBoxList($cuid, $stid = '') {
$cuid = $cuid;
$stid = $stid;
return view('report.BranchCheckBoxList', compact('cuid','stid'));
}
$(document).on('change','#cu',function(){
{
var state = $('#state option:selected').val();
var cu = $('#cu option:selected').val();
var viewurl = '{{ route("admin.booking.view", [":state",":cu"]) }}';
viewurl = viewurl.replace(':state',state );
var finalurl = viewurl.replace(':cu',cu );
$('a.btn').attr('href',finalurl);
});
and in you route
Route::get('reporting/branchCheckBoxList/{cuid}/{stid?}','GenReportController#branchCheckBoxList')->name('reporting.branchCheckBoxList');
and final in your controller
public function branchCheckBoxList($cuid, $stid = '')
{
$cuid = $cuid;
$stid = $stid;
return view('report.BranchCheckBoxList', compact('cuid','stid'));
}

How to display a table in a popup box with JavaScript?

I have the form below, with 4 comboboxes "Metier" "tache" "tacrification" et "technicien", I select a Metier and a tache, after this I want that a popup box appears and show me a table that contains all the "techniciens" and their "tarification" (of course only the "techniciens" that are related with the "tache" already selected.)
After this I select a "technicien" from that table a now the form is completely filled with the "technicien" and it's "tarification".
iterventioncontroller
public function create()
{
$client = client::orderBy('id', 'asc')->get();
$metiers = metier::orderBy('id', 'asc')->get();
$technicien = Technicien::orderBy('id', 'desc')->get();
$tarifications = tarificationtache::orderBy('id', 'desc')->get();
return view('intervention.create')->with('technicien', $technicien)-
>with('client',$client)-
>with('metiers',$metiers)->with('tarifications',$tarifications);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(InterventionRequest $request)
{
$intervention = new Intervention();
$intervention ->date_intervention =$request-
>input('date_intervention');
$intervention ->description =$request->input('description');
$intervention ->duree_prevu =$request->input('duree_prevu');
if($request->has('statut')){
$intervention->statut = $request->input('statut');
}else{
$intervention->statut = 0;
}
$intervention ->technicien_id = $request->input('technicien_id');
$intervention ->client_id = $request->input('client_id');
$intervention ->tarification_id = $request->tarification_id;
$intervention->save();
return redirect('intervention');
}
create.blade.php
#extends('Layouts/app')
#extends('Layouts/master')
#section('content')
<!-- jQuery -->
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
var getTachesByMetierUrl = "{{url('/tachesbymetier')}}";
var getAdresseByClientUrl = "{{url('/adressebyclient')}}";
var getTarificationsByTacheUrl = "{{url('/tarificationsbytache')}}";
var getTechniciensByTarificationtacheUrl = "
{{url('/techniciensbytarificationtache')}}";
//console.log(getMetiersByTechnicienUrl,getTachesByMetierUrl,getTarificationsByTacheUrl);
function getAdresseByClient(val) {
if(val.length>0) {
var client_id = val;
$.get(getAdresseByClientUrl+'/'+client_id,function(res) {
var html = '<option value="">-Select-</option>' ;
$.each(res.adresses,function(index,item) {
html+='<option
value="'+item.id+'">'+item.code_postal+'</option>';
});
$('#adresses').html(html);
});
}
}
function getTachesByMetier(val) {
if(val.length>0) {
var metier_id = val;
$.get(getTachesByMetierUrl+'/'+metier_id,function(res) {
var html = '<option value="">-Select-</option>' ;
$.each(res.taches,function(index,item) {
html+='<option
value="'+item.id+'">'+item.libelle_tache+'</option>';
});
$('#taches').html(html);
});
}
}
function getTarificationsByTache(val) {
if(val.length>0) {
var tache_id = val;
$.get(getTarificationsByTacheUrl+'/'+tache_id,function(res) {
var html = '<option value="">-Select-</option>' ;
$.each(res.tarifications,function(index,item) {
html+='<option
value="'+item.id+'">'+item.tarif+'</option>';
});
$('#tarifications').html(html);
});
}
}
function getTechniciensByTarificationtache(val) {
if(val.length>0) {
var tarificationtache_id = val;
$.get(getTechniciensByTarificationtacheUrl+'/'+tarificationtache_id,function(res) {
var html = '<option value="">-Select-</option>' ;
$.each(res.techniciens,function(index,item) {
html+='<option value="'+item.id+'">'+item.id+'</option>';
});
$('#techniciens').html(html);
});
}
}
#if(count($errors))
<div class="alert alert-danger" role="alert">
<ul>
#foreach($errors ->all() as $message)
<li>{{$message}}</li>
#endforeach
</ul>
</div>
#endif
<div class="container">
<div class="row"></div>
<div class="col-md-10">
<h1>Ajout Intervention</h1>
<form action=" {{url ('intervention') }}" method="post">
{{csrf_field()}}
<div class="form-group">
<label for="client">Client</label>
<select onchange="getAdresseByClient(this.value)"
name="client_id" id="client"
class="form-control">
<option value="">-Select-</option>
#foreach($client as $t)
<option value="{{$t->id }}">
{{$t->user->nom}}
</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="">date intervention</label>
<input class="form-control" type="date" id="example-date-
input" name
="date_intervention" value="{{old('date_intervention')}}">
</div>
<div class="form-group">
<label for="">description</label>
<input type="text" name ="description" class="form-
control"value="
{{old('description')}}">
</div>
<div class="form-group">
<label for="">duree_prevu</label>
<input class="form-control" type="datetime-local" name
="duree_prevu" value="
{{old('duree_prevu')}}">
</div>
<div class="form-group">
<div class="col-md-12">
<div class="col-md-4">
<label>Metier: </label>
<select onchange="getTachesByMetier(this.value)"
style="width: 200px"
class="productm form-control" id="metiers">
<option value="">-Select-</option>
#foreach($metiers as $t)
<option value="{{$t->id }}">
{{$t->libelle_metier}}
</option>
#endforeach
</select>
</div>
<div class="col-md-4">
<label>tache: </label>
<select onchange="getTarificationsByTache(this.value)"
style="width: 200px"
class="productname form-control" name="tache" id="taches">
<option value="">-Select-</option>
</select>
</div>
<div class="col-md-4">
<label>tarification: </label>
<select
onchange="getTechniciensByTarificationtache(this.value)"
style="width:
200px" class="productname form-control" name="tarificationtache_id"
id="tarifications">
<option value="">-Select-</option>
</select>
</div>
<div class="col-md-4">
<label>technicien: </label>
<select style="width: 200px" class="productname
form-control"
name="technicien_id" id="techniciens">
<option value="">-Select-</option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
<link
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-
datepicker/1.5.0/css/bootstrap-
datepicker.css" rel="stylesheet">
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-
datepicker/1.5.0/js/bootstrap-
datepicker.js"></script>
#endsection
You might want to look into bootstrap 4 modal.

Categories