我有一個 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 :
在你的視圖中的某個地方加入: