Compare commits

...

7 Commits

Author SHA1 Message Date
yash 2ce4691231 Made index page responsive 2024-07-25 11:28:48 +05:30
yash c4c52ac0af Bug fixes 2024-07-25 10:46:43 +05:30
Yash b6b8642496 Fixed profile button bug 2024-07-25 03:01:25 +05:30
Yash f83295fdfd Changed UI of viewResponse Page 2024-07-25 02:51:51 +05:30
Yash d4ad6e9a47 Fixed bug on the form responding page 2024-07-25 02:46:46 +05:30
Yash 87e0486962 Fixed bugs in edit form, Added softDelete, Added form_snapshot to save the older responses even after editing the form 2024-07-25 01:11:19 +05:30
yash 93916d6cde Flash message and UI changes 2024-07-24 17:24:47 +05:30
17 changed files with 449 additions and 220 deletions

View File

@ -1,7 +1,7 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Models\Form;
use App\Models\User;
@ -104,7 +104,6 @@ Contact us at (123) 456-7890 or no_reply@example.com
public function store(Request $request)
{
try {
$validatedData = $request->validate([
'title' => 'required|string|max:255',
'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.*.text' => 'required|string',
'questions.*.options' => 'nullable|array',
'questions.*.required' => 'nullable|boolean',
'questions.*.required' => 'boolean',
]);
DB::beginTransaction();
$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();
try {
$form = Form::create([
'title' => $validatedData['title'],
'description' => $validatedData['description'],
'user_id' => Auth::id(),
]);
foreach ($validatedData['questions'] as $questionData) {
$question = new Question();
$question->form_id = $form->id;
$question->type = $questionData['type'];
$question->question_text = $questionData['text'];
$question->options = isset($questionData['options']) ? json_encode($questionData['options']) : null;
$question->required = isset($questionData['required']) ? $questionData['required'] : false;
$question = new Question([
'form_id' => $form->id,
'type' => $questionData['type'],
'question_text' => $questionData['text'],
'options' => json_encode($questionData['options'] ?? []),
'required' => $questionData['required'],
]);
$question->save();
}
return response()->json(['success' => true, 'form_id' => $form->id]);
DB::commit();
return response()->json(['success' => true, 'message' => 'Form saved successfully.']);
} catch (\Exception $e) {
Log::error('Error saving form: ' . $e->getMessage(), ['exception' => $e]);
return response()->json(['success' => false, 'message' => 'Error saving form'], 500);
DB::rollBack();
Log::error('Error saving form: ' . $e->getMessage());
return response()->json(['success' => false, 'message' => 'Failed to save form.']);
}
}
@ -157,14 +158,21 @@ Contact us at (123) 456-7890 or no_reply@example.com
public function update(Request $request, Form $form)
{
if ($request->has('publish')) {
$form->is_published = !$form->is_published;
$form->save();
return redirect()->route('forms.show', $form);
try {
// Normalize the 'required' field to boolean
if ($request->has('questions')) {
$questions = $request->input('questions');
foreach ($questions as $index => $question) {
if (isset($question['required']) && $question['required'] === 'on') {
$questions[$index]['required'] = true;
} else {
$questions[$index]['required'] = false;
}
}
$request->merge(['questions' => $questions]);
}
Log::info('Incoming request data: ', $request->all());
// Validate the request
$validatedData = $request->validate([
'title' => 'required|string|max:255',
'description' => 'nullable|string|max:255',
@ -174,50 +182,38 @@ Contact us at (123) 456-7890 or no_reply@example.com
'questions.*.text' => 'required|string|max:255',
'questions.*.options' => 'nullable|array',
'questions.*.options.*' => 'nullable|string|max:255',
'questions.*.required' => 'boolean',
]);
Log::info('Validated data: ', $validatedData);
// Update form
$form->update([
'title' => $validatedData['title'],
'description' => $validatedData['description'],
]);
$existingQuestionIds = [];
// Clear existing questions
$form->questions()->delete();
// Create or update questions
foreach ($validatedData['questions'] as $questionData) {
if (isset($questionData['id'])) {
$question = Question::find($questionData['id']);
} else {
$question = new Question();
$question->form_id = $form->id;
}
$question->type = $questionData['type'];
$question->question_text = $questionData['text'];
$question->options = isset($questionData['options']) ? json_encode($questionData['options']) : json_encode([]);
$question = new Question([
'form_id' => $form->id,
'type' => $questionData['type'],
'question_text' => $questionData['text'],
'options' => json_encode($questionData['options'] ?? []),
'required' => $questionData['required'],
]);
$question->save();
Log::info('Saved question: ', $question->toArray());
$existingQuestionIds[] = $question->id;
}
$form->questions()->whereNotIn('id', $existingQuestionIds)->delete();
Log::info('Remaining questions: ', $form->questions()->get()->toArray());
DB::commit();
return redirect()->route('forms.show', $form)->with('success', 'Form updated successfully.');
} catch (\Exception $e) {
DB::rollBack();
Log::error('Error updating form: ' . $e->getMessage());
return back()->withErrors(['error' => 'An error occurred while updating the form. Please try again.'])->withInput();
}
}

View File

@ -31,33 +31,27 @@ class ResponseController extends Controller
public function viewResponse(Form $form, $responseId)
{
$responses = Response::where('response_id', $responseId)
->where('form_id', $form->id)
->get();
$questions = Question::where('form_id', $form->id)->get()->keyBy('id');
$statistics = [];
foreach ($questions as $question) {
$statistics[$question->id] = [
'question_text' => $question->question_text,
'type' => $question->type,
'options' => json_decode($question->options),
'responses' => []
];
foreach ($responses as $response) {
$decodedAnswers = json_decode($response->answers, true);
if (isset($decodedAnswers[$question->id])) {
$statistics[$question->id]['responses'][] = $decodedAnswers[$question->id];
}
}
if ($responses->isEmpty()) {
abort(404, 'Response not found');
}
return view('responses.viewResponse', compact('form', 'responses', 'questions', 'statistics'));
$formSnapshot = json_decode($responses->first()->form_snapshot, true);
if (is_null($formSnapshot) || !isset($formSnapshot['questions'])) {
Log::error('Form snapshot is null or does not contain questions', [
'response_id' => $responseId,
'form_snapshot' => $responses->first()->form_snapshot
]);
abort(500, 'Form snapshot is invalid');
}
$questions = collect($formSnapshot['questions'])->keyBy('id');
return view('responses.viewResponse', compact('form', 'responses', 'questions'));
}
@ -108,34 +102,39 @@ class ResponseController extends Controller
public function submitForm(Request $request, Form $form)
{
Log::info($request->all());
Log::info('Form submission started', $request->all());
$questions = $form->questions;
$requiredQuestionIds = $questions->where('required', true)->pluck('id')->toArray();
$validatedData = $request->validate([
'answers' => 'required|array',
'answers.*' => 'required',
'answers' => 'array',
'answers.*' => '',
]);
foreach ($requiredQuestionIds as $requiredQuestionId) {
if (!array_key_exists($requiredQuestionId, $validatedData['answers'])) {
return redirect()->back()
->withErrors(['errors' => 'Please answer all required questions.'])
->withInput();
if (!isset($validatedData['answers'][$requiredQuestionId]) || empty($validatedData['answers'][$requiredQuestionId])) {
return response()->json(['success' => false, 'message' => 'Please answer all required questions.']);
}
}
Log::info($validatedData);
Log::info('Validation passed', $validatedData);
$responseId = Uuid::uuid4()->toString();
$formSnapshot = [
'title' => $form->title,
'description' => $form->description,
'questions' => $questions->map(function ($question) {
return [
'id' => $question->id,
'question_text' => $question->question_text,
'type' => $question->type,
'options' => $question->options,
];
})->toArray(),
];
foreach ($validatedData['answers'] as $questionId => $answer) {
$response = new Response();
@ -145,10 +144,12 @@ class ResponseController extends Controller
$response->user_id = auth()->id();
$response->answers = json_encode($answer);
$response->submitted_at = now();
$response->form_snapshot = json_encode($formSnapshot);
$response->save();
Log::info('Response saved', $response->toArray());
}
return redirect()->route('responses.showForm', $form)
->with('success', 'Response submitted successfully.');
return response()->json(['success' => true, 'message' => 'Response submitted successfully.']);
}
}

View File

@ -1,25 +1,21 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Question extends Model
{
use SoftDeletes;
use HasFactory;
protected $fillable = ['form_id', 'user_id', 'submitted_at', 'answers'];
protected $fillable = ['form_id', 'type', 'question_text', 'options', 'required'];
protected $casts = [
'answers' => 'array',
'options' => 'array',
'required' => 'boolean',
];
public function getOptionsAttribute($value)
{
return json_decode($value, true);
}
public function form()
{
return $this->belongsTo(Form::class);

View File

@ -8,7 +8,7 @@ use Illuminate\Database\Eloquent\Model;
class Response extends Model
{
use HasFactory;
protected $fillable = ['form_id', 'user_id', 'answers'];
protected $fillable = ['form_id', 'user_id', 'response_id', 'question_id', 'answers', 'submitted_at', 'form_snapshot'];
// Define relationships
public function form()

View File

@ -0,0 +1,22 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up()
{
Schema::table('questions', function (Blueprint $table) {
$table->softDeletes();
});
}
public function down()
{
Schema::table('questions', function (Blueprint $table) {
$table->dropSoftDeletes();
});
}
};

View File

@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('responses', function (Blueprint $table) {
$table->json('form_snapshot')->nullable();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('responses', function (Blueprint $table) {
if (Schema::hasColumn('responses', 'form_snapshot')) {
$table->dropColumn('form_snapshot');
}
});
}
};

View File

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

View File

@ -6,7 +6,7 @@ document.addEventListener("DOMContentLoaded", function () {
const optionDiv = document.createElement("div");
optionDiv.className = "option";
optionDiv.innerHTML = `
<input type="text" class="form-control option-input" placeholder="New Option" />
<input type="text" class="form-control option-input mb-1" placeholder="New Option" />
<span class="delete-option" onclick="deleteOption(this)">&#10005;</span>
`;
optionContainer.appendChild(optionDiv);

View File

@ -62,7 +62,7 @@
<option value="dropdown">Dropdown</option>
<option value="text">Text</option>
</select>
<input style="border:none; border-bottom: 2px solid rgb(103,58,183); border-radius:0" type="text" name="question" class="form-control question-input mb-3" placeholder="Type your question here" />
<input style="border:none; border-bottom: 2px solid rgb(103,58,183); border-radius:0; color:black" type="text" name="question" class="form-control question-input mb-3" placeholder="Type your question here" />
<div class="options-container mb-3">
</div>

View File

@ -21,7 +21,7 @@
</head>
<body class="bg-purple-100">
<nav class="bg-white p-1 shadow-md">
<nav class="bg-white p-0.5 shadow-md">
<div class="container mx-auto flex justify-between items-center">
<span style="color: rgb(103,58,183)" class="text-3xl font-bold font-sans"><a href="{{ url('/') }}"
style="color: rgb(103,58,183)" class="text-3xl font-bold font-sans">LaraForms</a> - Edit</span>
@ -59,6 +59,7 @@
<div id="questions-section">
@foreach ($questions as $index => $question)
<div class="question mb-4 p-3 border rounded bg-light" data-index="{{ $index }}">
<input type="hidden" name="questions[{{ $index }}][id]" value="{{ $question->id }}">
<div class="form-group">
<select class="form-control question-type" id="question-type-{{ $index }}" name="questions[{{ $index }}][type]">
<option value="multiple_choice" {{ $question->type === 'multiple_choice' ? 'selected' : '' }}>Multiple Choice</option>
@ -88,7 +89,9 @@
</div>
@endforeach
@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);">
<img src="{{ asset('images/bin.png') }}" alt="" width="20px" height="20px" />
</button>
@ -111,7 +114,7 @@
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script>
function addOption(button) {
const optionsContainer = $(button).closest('.options-container');
const optionsContainer = $(button).closest('.question').find('.options-container');
const optionIndex = optionsContainer.find('.option').length;
const questionIndex = optionsContainer.closest('.question').data('index');
@ -137,6 +140,7 @@
const questionHtml = `
<div class="question mb-4 p-3 border rounded bg-light" data-index="${questionIndex}">
<input type="hidden" name="questions[${questionIndex}][id]" value="">
<div class="form-group">
<select class="form-control question-type" id="question-type-${questionIndex}" name="questions[${questionIndex}][type]" onchange="handleQuestionTypeChange(this)">
<option value="multiple_choice">Multiple Choice</option>
@ -149,14 +153,15 @@
<input type="text" id="question-text-${questionIndex}" name="questions[${questionIndex}][text]" class="form-control question-input" placeholder="Type your question here" required>
</div>
<div class="form-group form-check">
<input type="checkbox" id="question-required-{{ $index }}"
name="questions[{{ $index }}][required]" class="form-check-input"
{{ $question->required ? 'checked' : '' }}>
<label for="question-required-{{ $index }}" class="form-check-label">Required</label>
<input type="checkbox" id="question-required-${questionIndex}"
name="questions[${questionIndex}][required]" class="form-check-input">
<label for="question-required-${questionIndex}" class="form-check-label">Required</label>
</div>
<div class="form-group options-container">
<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);">
<img src="{{ asset('images/bin.png') }}" alt="" width="20px" height="20px" />
</button>
@ -239,16 +244,14 @@
});
updateAddButtonPosition();
$('#edit-form').on('submit', function(e) {
e.preventDefault();
updateQuestionIndices();
this.submit();
});
});
</script>
</body>
</html>

View File

@ -1,4 +1,4 @@
<!DOCTYPE html>
{{-- <!DOCTYPE html>
<html lang="en">
<head>
@ -9,10 +9,6 @@
<link href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
<style>
.dropdown:hover .dropdown-menu {
display: block;
}
.shadow-custom {
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}
@ -136,6 +132,11 @@
</div>
<script>
document.getElementById('profileMenuButton').addEventListener('click', function() {
var menu = document.getElementById('profileMenu');
menu.classList.toggle('hidden');
});
function handle() {
Swal.fire({
title: 'You cannot edit a published form',
@ -154,4 +155,156 @@
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
</body>
</html> --}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Forms</title>
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
<link href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
<style>
.shadow-custom {
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}
</style>
</head>
<body class="bg-gray-100">
<nav class="bg-white p-4 shadow-lg">
<div class="container mx-auto flex justify-between items-center">
<a href="{{ url('/') }}" class="text-3xl font-bold font-sans" style="color: rgb(103,58,183)">LaraForms</a>
<div class="relative dropdown">
<button id="profileMenuButton" class="flex items-center focus:outline-none">
<img src="{{ asset('images/user.png') }}" alt="Profile" class="w-10 h-10 rounded-full border-2 border-white">
</button>
<div id="profileMenu" class="dropdown-menu hidden absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-2">
<form method="POST" action="{{ route('logout') }}">
@csrf
<button type="submit" class="block px-4 py-2 text-gray-700 hover:bg-gray-200 w-full text-left">
Logout
</button>
</form>
</div>
</div>
</div>
</nav>
<div class="container mx-auto mt-10 px-4">
@if (session('success'))
<div class="bg-green-100 border border-green-400 text-green-700 px-4 py-2 rounded relative mt-4" role="alert">
<span class="block sm:inline">{{ session('success') }}</span>
</div>
@endif
@if (session('delete'))
<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-2 rounded relative mt-4" role="alert">
<span class="block sm:inline">{{ session('delete') }}</span>
</div>
@endif
<div class="flex flex-wrap justify-between mb-6 items-center space-y-4 lg:space-y-0 lg:space-x-4">
<a href="{{ route('forms.create') }}"
class="inline-block px-6 py-3 text-white font-semibold rounded-md shadow bg-purple-700 hover:bg-purple-900 transition duration-200">
Start a new form
</a>
<a class="block max-w-md w-full lg:w-1/4 p-5 bg-white border border-gray-200 rounded-lg shadow">
<h5 class="mb-2 text-gray-800 text-xl font-bold">Total Forms Created</h5>
<p class="font-normal text-gray-700">{{ $totalForms }}</p>
</a>
<a class="block max-w-md w-full lg:w-1/4 p-5 bg-white border border-gray-200 rounded-lg shadow">
<h5 class="mb-2 text-gray-800 text-xl font-bold">Total Forms Published</h5>
<p class="font-normal text-gray-700">{{ $publishedForms }}</p>
</a>
<a class="block max-w-md w-full lg:w-1/4 p-5 bg-white border border-gray-200 rounded-lg shadow">
<h5 class="mb-2 text-gray-800 text-xl font-bold">Total Responses Received</h5>
<p class="font-normal text-gray-700">{{ $totalResponses }}</p>
</a>
</div>
<hr>
<div class="mt-6">
<h2 class="text-3xl font-semibold text-gray-800 font-sans">Recent Forms</h2>
<div class="shadow-custom rounded-lg p-6 bg-gray-100 mt-4">
@if ($forms->isEmpty())
<p class="text-gray-600 text-center">No forms available.</p>
@else
<div class="overflow-x-auto">
<table class="min-w-full bg-white rounded-md">
<thead class="bg-gray-100">
<tr>
<th class="py-4 px-6 border-b border-gray-200 text-left text-sm font-semibold text-gray-600">Form Title</th>
<th class="py-4 px-6 border-b border-gray-200 text-left text-sm font-semibold text-gray-600">Created At</th>
<th class="py-4 px-6 border-b border-gray-200 text-left text-sm font-semibold text-gray-600">Responses</th>
<th class="py-4 px-6 border-b border-gray-200 text-left text-sm font-semibold text-gray-600">Status</th>
<th class="py-4 px-6 border-b border-gray-200"></th>
<th class="py-4 px-6 border-b border-gray-200"></th>
</tr>
</thead>
<tbody>
@foreach ($forms as $form)
<tr class="hover:bg-gray-50 transition duration-150">
<td class="py-4 px-6 border-b border-gray-200">
<a href="{{ route('forms.show', $form) }}" class="text-blue-600 font-semibold hover:underline">{{ $form->title }}</a>
<p class="text-gray-600">{{ $form->description }}</p>
</td>
<td class="py-4 px-6 border-b border-gray-200">{{ $form->created_at->format('M d, Y') }}</td>
<td class="py-4 px-6 border-b border-gray-200">
<a href="{{ route('responses.viewResponses', $form) }}" class="text-blue-500 hover:underline">View Responses</a>
</td>
<td class="py-4 px-6 border-b border-gray-200">
@if ($form->is_published)
Published
@else
Unpublished
@endif
</td>
<td class="py-8 px-6 border-b border-gray-200 flex items-center space-x-4">
@if (!$form->is_published)
<a href="{{ route('forms.edit', $form) }}" class="text-green-500 hover:underline">Edit</a>
@else
<a href="#" class="text-gray-500" id="formd" onclick="handle()">Edit</a>
@endif
</td>
<td class="border-b border-gray-200">
<form action="{{ route('forms.destroy', $form) }}" method="POST" class="inline-block">
@csrf
@method('DELETE')
<button type="submit" class="text-red-500 hover:underline">Delete</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endif
</div>
</div>
</div>
<script>
document.getElementById('profileMenuButton').addEventListener('click', function () {
var menu = document.getElementById('profileMenu');
menu.classList.toggle('hidden');
});
function handle() {
Swal.fire({
title: 'You cannot edit a published form',
icon: 'info',
confirmButtonText: 'OK'
});
}
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
</body>
</html>

View File

@ -35,6 +35,16 @@
</div>
</div>
</nav>
@if (session('success'))
<div class="bg-green-100 border border-green-400 text-green-700 px-4 py-2 rounded relative mt-4" role="alert">
<span class="block sm:inline">{{ session('success') }}</span>
</div>
@endif
@if (session('delete'))
<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-2 rounded relative mt-4" role="alert">
<span class="block sm:inline">{{ session('delete') }}</span>
</div>
@endif
<div class="question_form bg-gray-100 p-4 rounded shadow-sm">
<div class="section">
<div class="question_title_section mb-4">

View File

@ -8,7 +8,8 @@
<meta name="csrf-token" content="{{ csrf_token() }}">
<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 -->
<link rel="dns-prefetch" href="//fonts.bunny.net">
<link href="https://fonts.bunny.net/css?family=Nunito" rel="stylesheet">

View File

@ -12,7 +12,12 @@
@csrf
@foreach ($questions as $question)
<div class="mt-6">
<label class="block font-medium text-base text-gray-800 mb-2">{{ $question->question_text }}</label>
<label class="block font-medium text-base text-gray-800 mb-2">
{{ $question->question_text }}
@if ($question->required)
<span class="text-red-600">*</span>
@endif
</label>
@if ($question->type == 'multiple_choice')
@foreach (json_decode($question->options) as $option)
<label class="flex items-center mt-2">
@ -47,12 +52,33 @@
</div>
<script>
document.getElementById('responseForm').addEventListener('submit', function(event) {
document.addEventListener('DOMContentLoaded', function() {
const responseForm = document.getElementById('responseForm');
responseForm.addEventListener('submit', function(event) {
event.preventDefault();
const form = event.target;
const formData = new FormData(form);
let valid = true;
// @foreach ($questions as $question)
// @if ($question->required)
// const answer = formData.get('answers[{{ $question->id }}]');
// 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: {
@ -75,30 +101,24 @@
});
} else {
Swal.fire({
title: 'Success!',
text: 'Form submitted successfully.',
icon: 'success',
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: 'Success!',
text: 'Form submitted successfully.',
icon: 'success',
title: 'Error!',
text: 'There was an error submitting the form.',
icon: 'error',
confirmButtonText: 'OK'
}).then((result) => {
if (result.isConfirmed) {
window.location.href = '{{ route('responses.success', $form) }}';
}
});
});
}
});
});
</script>
@endsection

View File

@ -22,9 +22,10 @@
</div>
</header>
<div mt-4">
<div style="max-width: 100%;" class="container mt-4">
<!-- Responses Section -->
<div class="question_form bg-light p-4 rounded shadow-md" id="responses_section">
<div style="max-width: 100%;" class="question_form bg-light p-1 rounded shadow-md" id="responses_section">
<div class="section">
<div class="question_title_section mb-4">
<div class="question_form_top">
@ -36,25 +37,26 @@
<div class="section shadow-md" id="questions_section">
@foreach ($responses as $response)
@php
$question = $questions[$response->question_id] ?? null;
$question = $questions[$response->question_id];
$decodedAnswers = json_decode($response->answers, true);
@endphp
@if ($question)
<div class="question mb-4 p-3 border rounded bg-white shadow-md">
<h3 class="text-lg font-medium mb-2">{{ $question->question_text }}</h3>
@if ($question->type == 'dropdown')
<h3 class="text-lg font-medium mb-2">
{{ $question['question_text'] }}
</h3>
@if ($question['type'] == 'dropdown')
<select disabled class="form-control">
@foreach (json_decode($question->options) as $option)
@foreach (json_decode($question['options'] ?? '[]') as $option)
<option {{ ($option == $decodedAnswers) ? 'selected' : '' }}>
{{ $option }}
</option>
@endforeach
</select>
@elseif (in_array($question->type, ['multiple_choice', 'checkbox']))
@elseif (in_array($question['type'], ['multiple_choice', 'checkbox']))
<div class="options-container mb-3">
@foreach (json_decode($question->options) as $option)
@foreach (json_decode($question['options'] ?? '[]') as $option)
<div class="option d-flex align-items-center mb-2">
<input type="{{ $question->type == 'checkbox' ? 'checkbox' : 'radio' }}" disabled {{ in_array($option, (array)$decodedAnswers) ? 'checked' : '' }} class="mr-2">
<input type="{{ $question['type'] == 'checkbox' ? 'checkbox' : 'radio' }}" disabled {{ in_array($option, (array)$decodedAnswers) ? 'checked' : '' }} class="mr-2">
{{ $option }}
</div>
@endforeach
@ -63,9 +65,6 @@
<p class="mt-2 p-3 bg-light rounded">{{ is_array($decodedAnswers) ? implode(', ', $decodedAnswers) : $decodedAnswers }}</p>
@endif
</div>
@else
<p class="text-danger">Question not found for ID: {{ $response->question_id }}</p>
@endif
@endforeach
</div>
</div>

View File

@ -13,6 +13,7 @@
<body class="font-roboto text-gray-800 bg-white">
<!-- Header -->
<div class="bg-white shadow-md px-6 py-4 flex justify-between items-center">
<div class="flex items-center">

View File

@ -11,11 +11,4 @@ export default defineConfig({
refresh: true,
}),
],
server: {
host: '0.0.0.0',
port: 3000,
hmr: {
host: '192.168.2.179',
},
},
});