В моем проекте Laravel -5.8 я загружаю max_score при изменении Dropdown в зависимости от типа цели:
Все работает нормально, за исключением того, что проверка в некоторых случаях работает нормально и в других случаях не удалась.
CREATE TABLE `appraisal_goal_types` (
`id` int(11) NOT NULL,
`name` varchar(200) NOT NULL,
`parent_id` int(11) DEFAULT NULL,
`max_score` int(11) DEFAULT 0,
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
таблица: https://i.stack.imgur.com/hfVuJ.png
CREATE TABLE `appraisal_goals` (
`id` int(11) NOT NULL,
`goal_type_id` int(11) DEFAULT NULL,
`weighted_score` int(11) DEFAULT 0,
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Контроллер
public function findScore(Request $request)
{
$userCompany = Auth::user()->company_id;
$userEmployee = Auth::user()->employee_id;
$identities = DB::table('appraisal_identity')->select('id')->where('company_id', $userCompany)->where('is_current', 1)->first()->id;
$child = DB::table('appraisal_goal_types')->where('company_id', $userCompany)->where('id',$request->id)->first();
$parentid = DB::table('appraisal_goal_types')->select('parent_id')->where('company_id', $userCompany)->where('id',$request->id)->first()->parent_id;
if(empty($child))
{
abort(404);
}
$weightedscore = 0;
$weightedscore = DB::table('appraisal_goals')->select(DB::raw("SUM(weighted_score) as weighted_score"))->where('appraisal_identity_id', $identities)->where('employee_id', $userEmployee)->where('parent_id', $parentid)->get();
$maxscore = DB::table('appraisal_goal_types')->select('max_score')->find($child->parent_id);
return response()->json([
'maxscore' => $maxscore->max_score,
'weightedscore' => $weightedscore
]);
}
public function create()
{
$userCompany = Auth::user()->company_id;
$userEmployee = Auth::user()->employee_id;
$identities = DB::table('appraisal_identity')->select('id','appraisal_name')->where('company_id',
$userCompany)->where('is_current', 1)->first();
$goaltypes = AppraisalGoalType::where('company_id', $userCompany)->get();
$categories = AppraisalGoalType::with('children')->where('company_id', $userCompany)->whereNull('parent_id')->get();
return view('appraisal.appraisal_goals.create')
->with('goaltypes', $goaltypes)
->with('categories', $categories)
->with('identities', $identities)
;
}
маршрут / сеть. php
Route::resource('appraisal_goals', 'AppraisalGoalsController');
Route::get('get/findScore','Appraisal\AppraisalGoalsController@findScore')->name('get.scores.all');
Я отправляю max_score как json.
view
create.blade. php
<form action="{{route('appraisal.appraisal_goals.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<div class="card-body">
<div class="form-body">
<div class="row">
<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" 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('category_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('category_id') ? 'selected' : '' }}> {{ $child->name }}</option>
@endunless
@endforeach
@endif
@endunless
@endforeach
</select>
</div>
</div>
<input type="hidden" id="max_score" class="form-control" >
<input type="hidden" id="weighted_score" 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="number" name="weighted_score" id="total_weighted_score" placeholder="Enter weighted score here" class="form-control" max="120" onkeyup="checkScore(this.value)">
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$(document).on('change', '#goal_type', function() {
var air_id = $(this).val();
var a = $(this).parent();
console.log("Its Change !");
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[0]["weighted_score"]);
},
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>
Раскрывающийся список изменений загружает максимальный и взвешенный баллы.
По ключу в текстовом поле weighted_score, когда сумма weighted_score и загруженного взвешенного балла больше чем max_score для parent_id, система должна отправить предупреждение.
Удивительно, что он работает нормально, когда parent_id = 1 (цели рабочего плана), но не работает на других. Почему и как я это решаю?
Спасибо