我有一个可重用的引导模式组件,带有
{{ $slot }}
,我用它来渲染不同的 html 表单。这些表单是使用匿名刀片组件创建的。我需要一种方法来辨别之前显示的表单,然后使用 jQuery 重新显示它(如果表单提交后有任何验证 $errors
)。验证错误必须借助模式以正确的形式显示。该解决方案不得使用隐藏表单输入或查询字符串。目前,我使用了 Cookie 门面,我想知道这是否有点过分,因为我是从匿名刀片组件添加 cookie。
@inject('cookie', 'Illuminate\Support\Facades\Cookie')
<form action="{{ route('search-url') }}" method="post" id="search-form">
@csrf
{{ $cookie::queue('modalName', 'search-dialog', 2) }}
</form>
我能够从显示模态的视图中检索 cookie 值:
@section('scripts')
@parent
@if (count($errors) > 0 && ($targetModal = $cookie::get('modalName') ?? false))
<script type="module" src="{{ Storage::url('js/modal.errors.js') }}" id="modal-errors-js"
targetModal="#{{ $targetModal }}"></script>
@endif
@endsection
这是我用来实例化新的引导模式并显示它的脚本代码。
$(window).on("load", function () {
// Executes when complete page is fully loaded, including
// all frames, objects and images
const targetModal = $("#modal-errors-js").attr("targetModal");
const modalDialog = new bootstrap.Modal(targetModal);
modalDialog.toggle();
});
上面的代码片段工作正常,但我想知道是否有更好的方法来完成同样的任务。
我将 cookie 添加逻辑从匿名刀片组件移至 FormRequest 的受保护函数 failedValidation(Validator $validator): void{} 方法。我相信这是比从匿名刀片组件中添加 cookie 更好的方法。
更好的是:
我仍然希望社区审查这项技术并提供建设性的批评
/**
* Handle a failed validation attempt.
*
* @return void
*/
protected function failedValidation(Validator $validator): void
{
Cookie::queue('modalName', 'search-dialog', 2);
}