This is my Blade code for handling the form like my requirement is need to get the guard from the guard table need to store data in the rounds table as well as i need to store selected checkpoints
from the dropdown in the db table ,the guard data is storing perfectly but the checkpoints data is not storing im getting the error like this rounds rounds
3 / 4 requests
3.8 kB / 3.8 kB transferred
{message: “The selected checkpoints must be an array.”,…}
errors
:
{selected_checkpoints: [“The selected checkpoints must be an array.”]}
message
:
“The selected checkpoints must be an array.”
{!! Form::open(['class'=>'form-horizontal ajax_form','method'=>'POST','files' => true, 'autocomplete' => 'off']) !!}
<div class="row">
<!-- Left Column -->
<div class="col-md-6 col-sm-6">
<div class="portlet light bordered">
<!-- Title Start -->
<div class="portlet-title">
<div class="caption font-purple-wisteria">
<i class="fa fa-user font-purple-wisteria"></i>{!! trans('Round Details') !!}
</div>
</div>
<!-- Title -->
<!-- Body Start -->
<div class="portlet-body">
<!-- Add your left column form elements here -->
<div class="form-group">
<label class="col-md-3 control-label">{{ trans('Select Guard')}} <span class="required">* </span></label>
<div class="col-md-9">
<select class="form-control" name="guard">
@foreach ($guard as $guard)
<option value="{{ $guard->id }}">{{ $guard->full_name }}</option>
@endforeach
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">{{ trans('RoundName')}}<span class="required">* </span></label>
<div class="col-md-9">
<input type="text" class="form-control" name="roundname" id="roundname" placeholder="{{ trans('Roundname')}}" value="{{old('roundname')}}" disabled>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">{{ trans('StartTime')}}<span class="required">* </span></label>
<div class="col-md-9">
<input type="time" class="form-control" name="shiftstartTime" id="shiftstartTime" placeholder="{{ trans('core.shiftstartTime')}}" value="{{old('shiftstartTime')}}" onchange="updateRoundName()">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">{{ trans('EndTime')}}<span class="required">* </span></label>
<div class="col-md-9">
<input type="time" class="form-control" name="shiftendTime" id="shiftendTime" placeholder="{{ trans('core.shiftendTime')}}" value="{{old('shiftendTime')}}" onchange="updateRoundName()">
</div>
</div>
<hr>
<button type="button" style="margin: 1% 0 1% 25%;" onclick="addEmployee();return false;" class=" btn green ">
{{ trans('core.btnSubmit')}}
</button>
<!-- Add more left column form elements as needed -->
</div>
<!-- Body End -->
</div>
</div>
<!-- Right Column -->
<div class="col-md-6 col-sm-6">
<div class="portlet light bordered">
<!-- Title Start -->
<div class="portlet-title">
<!-- Add your right column form elements here -->
<div class="caption font-purple-wisteria">
<i class="fa fa-user font-purple-wisteria"></i>{!! trans('Add Your checkPoint Here!') !!}
</div>
</div>
<!-- Title End -->
<!-- Body Start -->
<div class="portlet-body">
<!-- Add your right column form elements here -->
<div class="form-group">
<div class="col-md-10">
<label>{{ trans('Select Checkpoint')}} <span class="required">* </span></label>
<input type="hidden" name="selected_checkpoints[]" id="selected_checkpoints" value="">
<select class="form-control" name="selected_checkpoints[]" id="checkpoint-select">
@foreach ($checkpoint as $checkpoint)
<option value="{{ $checkpoint->id }}">{{ $checkpoint->checkpointname }} {{ $checkpoint->id }}</option>
@endforeach
</select>
<button type="button" class="btn btn-success btn-sm" style="margin: 4% 14% 0% 0%;" id="add-checkpoint" onclick="addCheckpoint()">Add</button>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<table id="selected-checkpoints-table" class="table" style="background-color:#eff1f4;">
<thead>
<tr>
<th>Sr.No.</th>
<th>Checkpoint Name</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<!-- Selected checkpoints will be displayed here -->
</tbody>
</table>
</div>
</div>
</div>
<!-- Body End -->
</div>
</div>
<!-- Right column End -->
</div>
{!! Form::close() !!}
My js code
<script>
function addEmployee() {
// Clear any previous error messages
$('.form-group').removeClass('has-error');
$('.help-block').remove();
var isValid = true;
// Validate Full Name
var roundName = $('input[name="roundname"]').val().trim();
if (roundName === '') {
isValid = false;
$('input[name="roundname"]').closest('.form-group').addClass('has-error');
$('input[name="roundname"]').after('<span class="help-block">Round name is required.</span>');
}
if (isValid) {
// Collect selected checkpoint IDs
var selectedCheckpointIds = Array.from(document.querySelectorAll("#selected-checkpoints-table tbody tr")).map(function (row) {
return row.dataset.checkpointId;
});
// Attach selectedCheckpointIds to the form data
$('input[name="selected_checkpoints"]').remove(); // Remove any previous hidden input
$('<input>').attr({
type: 'hidden',
name: 'selected_checkpoints',
value: JSON.stringify(selectedCheckpointIds)
}).appendTo('.ajax_form');
// If all validations pass, proceed with form submission
var url = "{{ route('admin.rounds.store') }}";
$.easyAjax({
type: 'POST',
url: url,
container: '.ajax_form',
file: true,
});
}
}
// updating the roundname with the start time and endtime..
function updateRoundName() {
var startTime = document.getElementById('shiftstartTime').value.replace(':', ''); //it Remove colons
var endTime = document.getElementById('shiftendTime').value.replace(':', ''); // Remove colons
var roundnameField = document.getElementById('roundname'); // getting the roundname using the id..
// Combine the start time and end time without colons
var roundname = startTime + '-' + endTime;
// Update the "roundname" field value
roundnameField.value = roundname;
}
// Checkpoint data
// Initialize an array to store selected checkpoint IDs
var selectedCheckpointIds = [];
var rowCount = 1; // Initialize rowCount to 1
// Function to add the selected checkpoint to the selected_checkpoints field
function addSelectedCheckpoint(checkpointId) {
var selectedCheckpointsInput = document.getElementById("selected_checkpoints");
var selectedCheckpoints = selectedCheckpointsInput.value ? selectedCheckpointsInput.value.split(",") : [];
// Add the checkpointId to the selectedCheckpoints array
selectedCheckpoints.push(checkpointId);
// Update the selected_checkpoints field with the updated array
selectedCheckpointsInput.value = selectedCheckpoints.join(",");
}
// Function to remove the selected checkpoint from the selectedCheckpointIds array
function removeSelectedCheckpoint(checkpointId) {
var index = selectedCheckpointIds.indexOf(checkpointId);
if (index !== -1) {
selectedCheckpointIds.splice(index, 1);
}
}
function addCheckpoint() {
var selectBox = document.getElementById("checkpoint-select");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
var selectedText = selectBox.options[selectBox.selectedIndex].text;
if (selectedValue !== "") {
// Check if the checkpoint has already been added
var tableBody = document.querySelector("#selected-checkpoints-table tbody");
var rows = tableBody.rows;
for (var i = 0; i < rows.length; i++) {
var existingValue = rows[i].cells[1].textContent;
if (existingValue === selectedText) {
alert("Checkpoint already added.");
return;
}
}
// Create a new row in the table and append it
var newRow = tableBody.insertRow(tableBody.rows.length);
newRow.insertCell(0).textContent = rowCount++; // Increment rowCount
newRow.insertCell(1).textContent = selectedText;
var deleteCell = newRow.insertCell(2);
var deleteButton = document.createElement("button");
deleteButton.textContent = "Delete";
deleteButton.className = "btn btn-danger";
deleteButton.onclick = function () {
deleteRow(newRow);
addOptionToSelect(selectedValue, selectedText);
updateSno(); // Update the Sr.No.
updateDropdownMessage(); // Update the dropdown message
removeSelectedCheckpoint(selectedValue); // Remove this checkpoint from the selected_checkpoints field
};
deleteCell.appendChild(deleteButton);
// Clear the selected option and remove it from the dropdown
selectBox.remove(selectBox.selectedIndex);
// Update the dropdown message
updateDropdownMessage();
// Add the selected checkpoint ID to the selectedCheckpointIds array
selectedCheckpointIds.push(selectedValue);
// Update the hidden input field with the selected checkpoint IDs
document.getElementById("selected_checkpoints").value = selectedCheckpointIds.join(",");
// Add the selected checkpoint ID to the selected_checkpoints field
addSelectedCheckpoint(selectedValue);
}
}
function addOptionToSelect(value, text) {
var selectBox = document.getElementById("checkpoint-select");
var option = document.createElement("option");
option.value = value;
option.text = text;
selectBox.appendChild(option);
// Enable the dropdown when an option is added
selectBox.disabled = false;
// Update the dropdown message
updateDropdownMessage();
}
function deleteRow(row) {
var tableBody = document.querySelector("#selected-checkpoints-table tbody");
tableBody.removeChild(row);
updateSno(); // Update the Sr.No. after deletion
// Enable the dropdown when a row is deleted
var selectBox = document.getElementById("checkpoint-select");
selectBox.disabled = false;
// Update the dropdown message
updateDropdownMessage();
}
function updateSno() {
// Update the Sr.No. for all rows
var tableBody = document.querySelector("#selected-checkpoints-table tbody");
var rows = tableBody.rows;
for (var i = 0; i < rows.length; i++) {
rows[i].cells[0].textContent = i + 1;
}
rowCount = rows.length + 1; // Update the rowCount
}
function updateDropdownMessage() {
var selectBox = document.getElementById("checkpoint-select");
if (selectBox.options.length === 0) {
selectBox.innerHTML = '<option value="">No checkpoints available</option>';
selectBox.disabled = true;
} else {
// Remove the "No checkpoints available" option if it exists
var noCheckpointOption = selectBox.querySelector('option[value=""]');
if (noCheckpointOption) {
selectBox.removeChild(noCheckpointOption);
}
selectBox.disabled = false;
}
}
my laravel code looks something like this
public function store(Request $request)
{
// Validate the form data
$validatedData = $request->validate([
'guard' => 'required',
'shiftstartTime' => 'required',
'shiftendTime' => 'required',
'selected_checkpoints' => 'required|array', // Ensure selected_checkpoints is an array
'selected_checkpoints.*' => 'exists:checkpoints,id', // Validate that each checkpoint exists in the "checkpoints" table
]);
// Create a new round and save it
$round = new Round();
$round->guard_id = $validatedData['guard'];
$round->shiftstartTime = $validatedData['shiftstartTime'];
$round->shiftendTime = $validatedData['shiftendTime'];
$round->save();
// Attach selected checkpoints to the round
$round->checkpoints()->attach($validatedData['selected_checkpoints']);
// Redirect or return a response as needed
Errors
im getting the error like this how to resolve this while except checkpoint field all my fields are storing in the db but the checkpointsdata is not storing
Im getting the error like this rounds rounds
3 / 4 requests
3.8 kB / 3.8 kB transferred
{message: "The selected checkpoints must be an array.",…}
errors
:
{selected_checkpoints: ["The selected checkpoints must be an array."]}
message:"The selected checkpoints must be an array."