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,41 +104,42 @@ Contact us at (123) 456-7890 or no_reply@example.com
public function store(Request $request) public function store(Request $request)
{ {
$validatedData = $request->validate([
'title' => 'required|string|max:255',
'description' => 'nullable|string',
'questions' => 'required|array',
'questions.*.type' => 'required|string|in:multiple_choice,checkbox,dropdown,text',
'questions.*.text' => 'required|string',
'questions.*.options' => 'nullable|array',
'questions.*.required' => 'boolean',
]);
DB::beginTransaction();
try { try {
$validatedData = $request->validate([ $form = Form::create([
'title' => 'required|string|max:255', 'title' => $validatedData['title'],
'description' => 'nullable|string', 'description' => $validatedData['description'],
'questions' => 'required|array', 'user_id' => Auth::id(),
'questions.*.type' => 'required|string|in:multiple_choice,checkbox,dropdown,text',
'questions.*.text' => 'required|string',
'questions.*.options' => 'nullable|array',
'questions.*.required' => 'nullable|boolean',
]); ]);
$form = new Form();
$form->title = $validatedData['title'];
$form->description = $validatedData['description'];
$form->is_published = $request->input('is_published', false);
$form->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,72 +52,73 @@
</div> </div>
<script> <script>
document.getElementById('responseForm').addEventListener('submit', function(event) { document.addEventListener('DOMContentLoaded', function() {
event.preventDefault(); const responseForm = document.getElementById('responseForm');
responseForm.addEventListener('submit', function(event) {
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);
// if (!answer || !answer.trim()) {
// valid = false;
// Swal.fire({
// title: 'Error!',
// text: 'Please answer all required questions.',
// icon: 'error',
// confirmButtonText: 'OK'
// });
// return; // Exit the function to prevent further execution
// }
// @endif
// @endforeach
if (valid) {
fetch(form.action, {
method: form.method,
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
Swal.fire({
title: 'Success!',
text: 'Form submitted successfully.',
icon: 'success',
confirmButtonText: 'OK'
}).then((result) => {
if (result.isConfirmed) {
window.location.href = '{{ route('responses.success', $form) }}';
}
});
} else {
Swal.fire({
title: 'Error!',
text: 'Error submitting. Answer all required questions',
icon: 'error',
confirmButtonText: 'OK'
});
}
})
.catch(error => {
console.error('Error:', error);
Swal.fire({ Swal.fire({
title: 'Error!', title: 'Error!',
text: 'Please answer all required questions.', text: 'There was an error submitting the form.',
icon: 'error', icon: 'error',
confirmButtonText: 'OK' confirmButtonText: 'OK'
}); });
break;
}
@endif
@endforeach
if (valid) {
fetch(form.action, {
method: form.method,
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
Swal.fire({
title: 'Success!',
text: 'Form submitted successfully.',
icon: 'success',
confirmButtonText: 'OK'
}).then((result) => {
if (result.isConfirmed) {
window.location.href = '{{ route('responses.success', $form) }}';
}
});
} else {
Swal.fire({
title: 'Error!',
text: 'Error submitting. Answer all required questions',
icon: 'error',
confirmButtonText: 'OK'
}).then((result) => {
if (result.isConfirmed) {
window.location.href = '{{ route('responses.success', $form) }}';
}
});
}
})
.catch(error => {
console.error('Error:', error);
Swal.fire({
title: 'Error!',
text: 'There was an error submitting the form.',
icon: 'error',
confirmButtonText: 'OK'
}); });
}); }
} });
}); });
</script> </script>
@endsection @endsection