Fixed bug on the form responding page

This commit is contained in:
Yash 2024-07-25 02:46:46 +05:30
parent 87e0486962
commit d4ad6e9a47
5 changed files with 101 additions and 91 deletions

View File

@ -104,7 +104,6 @@ Contact us at (123) 456-7890 or no_reply@example.com
public function store(Request $request) public function store(Request $request)
{ {
try {
$validatedData = $request->validate([ $validatedData = $request->validate([
'title' => 'required|string|max:255', 'title' => 'required|string|max:255',
'description' => 'nullable|string', 'description' => 'nullable|string',
@ -112,33 +111,35 @@ Contact us at (123) 456-7890 or no_reply@example.com
'questions.*.type' => 'required|string|in:multiple_choice,checkbox,dropdown,text', 'questions.*.type' => 'required|string|in:multiple_choice,checkbox,dropdown,text',
'questions.*.text' => 'required|string', 'questions.*.text' => 'required|string',
'questions.*.options' => 'nullable|array', 'questions.*.options' => 'nullable|array',
'questions.*.required' => 'nullable|boolean', 'questions.*.required' => 'boolean',
]); ]);
DB::beginTransaction();
$form = new Form(); try {
$form->title = $validatedData['title']; $form = Form::create([
$form->description = $validatedData['description']; 'title' => $validatedData['title'],
$form->is_published = $request->input('is_published', false); 'description' => $validatedData['description'],
$form->user_id = Auth::id(); 'user_id' => Auth::id(),
$form->save(); ]);
foreach ($validatedData['questions'] as $questionData) { foreach ($validatedData['questions'] as $questionData) {
$question = new Question(); $question = new Question([
$question->form_id = $form->id; 'form_id' => $form->id,
$question->type = $questionData['type']; 'type' => $questionData['type'],
$question->question_text = $questionData['text']; 'question_text' => $questionData['text'],
$question->options = isset($questionData['options']) ? json_encode($questionData['options']) : null; 'options' => json_encode($questionData['options'] ?? []),
$question->required = isset($questionData['required']) ? $questionData['required'] : false; 'required' => $questionData['required'],
]);
$question->save(); $question->save();
} }
DB::commit();
return response()->json(['success' => true, 'message' => 'Form saved successfully.']);
return response()->json(['success' => true, 'form_id' => $form->id]);
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Error saving form: ' . $e->getMessage(), ['exception' => $e]); DB::rollBack();
return response()->json(['success' => false, 'message' => 'Error saving form'], 500); Log::error('Error saving form: ' . $e->getMessage());
return response()->json(['success' => false, 'message' => 'Failed to save form.']);
} }
} }

View File

@ -255,3 +255,7 @@ input:focus, textarea:focus, select:focus{
color: black; color: black;
height: 20px; height: 20px;
} }
.active-question {
border-left: 4px solid blue;
}

View File

@ -89,7 +89,9 @@
</div> </div>
@endforeach @endforeach
@endif @endif
<button type="button" class="btn btn-secondary" onclick="addOption(this)">Add Option</button> </div>
<div class="d-flex align-items-center mt-2">
<button type="button" class="btn btn-secondary mr-2" onclick="addOption(this)">Add Option</button>
<button class="btn btn-md" id="moveUpButton" onclick="deleteQuestion(this);"> <button class="btn btn-md" id="moveUpButton" onclick="deleteQuestion(this);">
<img src="{{ asset('images/bin.png') }}" alt="" width="20px" height="20px" /> <img src="{{ asset('images/bin.png') }}" alt="" width="20px" height="20px" />
</button> </button>
@ -112,7 +114,7 @@
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script> <script>
function addOption(button) { function addOption(button) {
const optionsContainer = $(button).closest('.options-container'); const optionsContainer = $(button).closest('.question').find('.options-container');
const optionIndex = optionsContainer.find('.option').length; const optionIndex = optionsContainer.find('.option').length;
const questionIndex = optionsContainer.closest('.question').data('index'); const questionIndex = optionsContainer.closest('.question').data('index');
@ -152,13 +154,14 @@
</div> </div>
<div class="form-group form-check"> <div class="form-group form-check">
<input type="checkbox" id="question-required-${questionIndex}" <input type="checkbox" id="question-required-${questionIndex}"
name="questions[${questionIndex}][required]" class="form-check-input" name="questions[${questionIndex}][required]" class="form-check-input">
{{ $question->required ? 'checked' : '' }}>
<label for="question-required-${questionIndex}" class="form-check-label">Required</label> <label for="question-required-${questionIndex}" class="form-check-label">Required</label>
</div> </div>
<div class="form-group options-container"> <div class="form-group options-container">
<label>Options</label> <label>Options</label>
<button type="button" class="btn btn-secondary" onclick="addOption(this)">Add Option</button> </div>
<div class="d-flex align-items-center mt-2">
<button type="button" class="btn btn-secondary mr-2" onclick="addOption(this)">Add Option</button>
<button class="btn btn-md" id="moveUpButton" onclick="deleteQuestion(this);"> <button class="btn btn-md" id="moveUpButton" onclick="deleteQuestion(this);">
<img src="{{ asset('images/bin.png') }}" alt="" width="20px" height="20px" /> <img src="{{ asset('images/bin.png') }}" alt="" width="20px" height="20px" />
</button> </button>

View File

@ -8,7 +8,8 @@
<meta name="csrf-token" content="{{ csrf_token() }}"> <meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'LaraForms') }}</title> <title>{{ config('app.name', 'LaraForms') }}</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!-- Fonts --> <!-- Fonts -->
<link rel="dns-prefetch" href="//fonts.bunny.net"> <link rel="dns-prefetch" href="//fonts.bunny.net">
<link href="https://fonts.bunny.net/css?family=Nunito" rel="stylesheet"> <link href="https://fonts.bunny.net/css?family=Nunito" rel="stylesheet">

View File

@ -52,27 +52,31 @@
</div> </div>
<script> <script>
document.getElementById('responseForm').addEventListener('submit', function(event) { document.addEventListener('DOMContentLoaded', function() {
const responseForm = document.getElementById('responseForm');
responseForm.addEventListener('submit', function(event) {
event.preventDefault(); event.preventDefault();
const form = event.target; const form = event.target;
const formData = new FormData(form); const formData = new FormData(form);
let valid = true; let valid = true;
@foreach ($questions as $question) // @foreach ($questions as $question)
@if ($question->required) // @if ($question->required)
if (!formData.has('answers[{{ $question->id }}]') || !formData.get('answers[{{ $question->id }}]').trim()) { // const answer = formData.get('answers[{{ $question->id }}]');
valid = false; // console.log('Question ID:', {{ $question->id }}, 'Answer:', answer);
Swal.fire({ // if (!answer || !answer.trim()) {
title: 'Error!', // valid = false;
text: 'Please answer all required questions.', // Swal.fire({
icon: 'error', // title: 'Error!',
confirmButtonText: 'OK' // text: 'Please answer all required questions.',
}); // icon: 'error',
break; // confirmButtonText: 'OK'
} // });
@endif // return; // Exit the function to prevent further execution
@endforeach // }
// @endif
// @endforeach
if (valid) { if (valid) {
fetch(form.action, { fetch(form.action, {
@ -101,10 +105,6 @@
text: 'Error submitting. Answer all required questions', text: 'Error submitting. Answer all required questions',
icon: 'error', icon: 'error',
confirmButtonText: 'OK' confirmButtonText: 'OK'
}).then((result) => {
if (result.isConfirmed) {
window.location.href = '{{ route('responses.success', $form) }}';
}
}); });
} }
}) })
@ -119,5 +119,6 @@
}); });
} }
}); });
});
</script> </script>
@endsection @endsection