我有一个 Laravel 应用程序,在视图页面上有一个模式框,允许用户将数据添加到数据库。默认情况下,当用户点击提交按钮,后端返回错误时,模态框消失。我想在发生错误时保持模式框可见。我怎样才能实现这个目标?
触发模态框的按钮
<div><button class="add" data-modal-target="#modal-box">Add New Year</button></div>
我的模态框
<div class="modal-box" id="modal-box"> <div class="modal-header"> <div class="title"><h1>Create School Year</h1></div> <div data-close-button class="modal-close-btn"> <span class="material-symbols-sharp">close</span> </div> </div> <hr> <div class="modal-body"> <form action="{{ route('create.year') }}" method="post"> @csrf <div class="input-form"> <div class="form-group"> <h3>School Year <span class="danger">*</span></h3> <input type="text" name="name" id="name"> @error('name') <p class="error danger">{{ $message }}</p> @enderror </div> <div> <button type="submit" class="create">Create Year</button> </div> </div> </form> </div> </div>
JavaScript 切换模态框
const openModalButtons = document.querySelectorAll("[data-modal-target]"); const closeModalButtons = document.querySelectorAll("[data-close-button]"); const overlay = document.getElementById("overlay"); openModalButtons.forEach((button) => { button.addEventListener("click", () => { const modal = document.querySelector(button.dataset.modalTarget); openModal(modal); }); }); closeModalButtons.forEach((button) => { button.addEventListener("click", () => { const modal = button.closest(".modal-box"); closeModal(modal); }); }); overlay.addEventListener("click", () => { const modals = document.querySelectorAll(".modal-box.active"); modals.forEach((modal) => { closeModal(modal); }); }); function openModal(modal) { if (modal == null) return; modal.classList.add("active"); overlay.classList.add("active"); } function closeModal(modal) { if (modal == null) return; modal.classList.remove("active"); overlay.classList.remove("active"); }
我的控制器
public function CreateYear(Request $request) { $validateData = $request->validate([ 'name' => 'required|unique:academic_years,name' ]); $data = new AcademicYear(); $data->name = $request->name; $data->save(); $notification = array( 'message' => 'Academic Year Created Successfully!', 'alert-type' => 'success' ); return redirect()->route('view.year')->with($notification); }
在您的表单中,您可以添加一个带有模式 ID 的隐藏输入。在控制器中提交时,您将获得 id 并将其以变量形式返回。当返回视图时,您检查该变量是否存在,如果存在,则调用相应的模态 open :
在你的视图中的某个地方添加: