如何在Laravel中的模态表单中进行唯一字段验证期间显示警告错误?

huangapple go评论52阅读模式
英文:

how to show alert errors during validation of unique field in modal form using laravel

问题

我正在使用Laravel,并且我是新手。我在"货币"视图中有一个模态表单,一切都正常,但我遇到了一个问题,当我点击保存按钮并且"CurrencyName"重复时,我会收到一个警告,但是我是在关闭模态表单并返回到"货币"页面后才收到这个警告的。

以下是在"货币"视图页面中的代码:

<div class="d-flex my-xl-auto right-content">
    <a class="modal-effect btn-block" data-effect="effect-scale" data-toggle="modal" href="#modaldemo8">
        <button type="button" class="btn btn-success btn-icon ml-2">
            <i class="mdi mdi-plus"></i>
        </button>
    </a>
</div>
<div class="modal" id="modaldemo8" style="display: none;" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content modal-content-demo">
            <div class="modal-header">
                <h6 class="modal-title">新建</h6>
                <button aria-label="Close" class="close" data-dismiss="modal" type="button">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <div class="modal-body">
                <form class="needs-validation was-validated" action="{{ route('currencies.store') }}" method="POST">
                    @csrf
                    <div class="row row-sm">
                        <div class="col-lg-12">
                            <div class="form-group row">
                                <label for="txtcurrencytype" class="col-lg-2 col-form-label">类型</label>
                                <div class="col-lg-10">
                                    <input type="text" class="form-control" id="txtcurrencytype" name="txtcurrencytype" value="forg" disabled>
                                </div>
                            </div>

                            <div class="form-group row">
                                <label for="txtcurrencyname" class="col-lg-2 col-form-label">货币名称</label>
                                <div class="col-lg-10">
                                    <input type="text" class="form-control" id="txtcurrencyname" name="CurrencyName" required>
                                </div>
                            </div>

                            <div class="form-group row">
                                <label for="txtcurrencyprice1" class="col-lg-2 col-form-label">价格1</label>
                                <div class="col-lg-10">
                                    <input type="number" class="form-control" id="txtcurrencyprice1" name="txtcurrencyprice1" step="any" required>
                                </div>
                            </div>

                            <div class="form-group row">
                                <label for="txtcurrencyprice2" class="col-lg-2 col-form-label">价格2</label>
                                <div class="col-lg-10">
                                    <input type="number" class="form-control" id="txtcurrencyprice2" name="txtcurrencyprice2" step="any" required>
                                </div>
                            </div>

                            <!-- 错误 -->
                            @if ($errors->any())
                            <div class="alert alert-danger">
                                <ul>
                                    @foreach ($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                    @endforeach
                                </ul>
                            </div>
                            @endif
                            <!-- 错误 -->
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button class="btn ripple btn-primary" type="submit">保存</button>
                        <button class="btn ripple btn-secondary" data-dismiss="modal" type="button">取消</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

控制器部分:

public function store(Request $request)
{
    $validatedData = $request->validate(
        [
            'CurrencyName' => ['unique:tblcurrencies', 'max:50']
        ],
        [
            'CurrencyName.unique' => '错误1!',
            'CurrencyName.max' => '错误2!'
        ]
    );

    Currency::create(
        [
            'CurrencyRef' => Helper::GetNewRef(),
            'CurrencyName' => $request['CurrencyName'],
            'CurrencyPrice1' => $request['txtcurrencyprice1'],
            'CurrencyPrice2' => $request['txtcurrencyprice2'],
            'CurrentUser' => auth()->id()
        ]
    );

    if ($request->ajax()) {
        return response()->json(['success' => true]);
    }

    return redirect()->back();
}

我需要的是,当我点击"保存"按钮时(如果有任何错误),我希望在模态表单中显示警告,而不关闭模态表单。

英文:

I'm working with Laravel and I'm new there.
I have a modal form in currencies view everything is ok but I have a problem that when I click on save button and the "CurrencyName" is duplicate I got an alert but I got that alert after closing the modal form and get back to "currencies" page.

the following code in "currencies" view page:

 &lt;div class=&quot;d-flex my-xl-auto right-content&quot;&gt;
&lt;a class=&quot;modal-effect btn-block&quot; data-effect=&quot;effect-scale&quot; data-toggle=&quot;modal&quot; href=&quot;#modaldemo8&quot;&gt;
&lt;button type=&quot;button&quot; class=&quot;btn btn-success btn-icon ml-2&quot;&gt;
&lt;i class=&quot;mdi mdi-plus&quot;&gt;&lt;/i&gt;
&lt;/button&gt;
&lt;/a&gt;
&lt;/div&gt;
&lt;div class=&quot;modal&quot; id=&quot;modaldemo8&quot; style=&quot;display: none;&quot; aria-hidden=&quot;true&quot;&gt;
&lt;div class=&quot;modal-dialog modal-dialog-centered&quot; role=&quot;document&quot;&gt;
&lt;div class=&quot;modal-content modal-content-demo&quot;&gt;
&lt;div class=&quot;modal-header&quot;&gt;
&lt;h6 class=&quot;modal-title&quot;&gt;new&lt;/h6&gt;&lt;button aria-label=&quot;Close&quot; class=&quot;close&quot; data-dismiss=&quot;modal&quot; type=&quot;button&quot;&gt;&lt;span aria-hidden=&quot;true&quot;&gt;&#215;&lt;/span&gt;&lt;/button&gt;
&lt;/div&gt;
&lt;div class=&quot;modal-body&quot;&gt;
&lt;form class=&quot;needs-validation was-validated&quot; action=&quot;{{ route(&#39;currencies.store&#39;) }}&quot; method=&quot;POST&quot;&gt;
@csrf
&lt;div class=&quot;row row-sm&quot;&gt;
&lt;div class=&quot;col-lg-12&quot;&gt;
&lt;div class=&quot;form-group row&quot;&gt;
&lt;label for=&quot;txtcurrencytype&quot; class=&quot;col-lg-2 col-form-label&quot;&gt;type&lt;/label&gt;
&lt;div class=&quot;col-lg-10&quot;&gt;
&lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;txtcurrencytype&quot; name=&quot;txtcurrencytype&quot; value=&quot;forg&quot; disabled&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;form-group row&quot;&gt;
&lt;label for=&quot;txtcurrencyname&quot; class=&quot;col-lg-2 col-form-label&quot;&gt;currency name&lt;/label&gt;
&lt;div class=&quot;col-lg-10&quot;&gt;
&lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;txtcurrencyname&quot; name=&quot;CurrencyName&quot; required&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;form-group row&quot;&gt;
&lt;label for=&quot;txtcurrencyprice1&quot; class=&quot;col-lg-2 col-form-label&quot;&gt;price1&lt;/label&gt;
&lt;div class=&quot;col-lg-10&quot;&gt;
&lt;input type=&quot;number&quot; class=&quot;form-control&quot; id=&quot;txtcurrencyprice1&quot; name=&quot;txtcurrencyprice1&quot; step=&quot;any&quot; required&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;form-group row&quot;&gt;
&lt;label for=&quot;txtcurrencyprice2&quot; class=&quot;col-lg-2 col-form-label&quot;&gt;price2&lt;/label&gt;
&lt;div class=&quot;col-lg-10&quot;&gt;
&lt;input type=&quot;number&quot; class=&quot;form-control&quot; id=&quot;txtcurrencyprice2&quot; name=&quot;txtcurrencyprice2&quot; step=&quot;any&quot; required&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;!-- Errors --&gt;
@if ($errors-&gt;any())
&lt;div class=&quot;alert alert-danger&quot;&gt;
&lt;ul&gt;
@foreach ($errors-&gt;all() as $error)
&lt;li&gt;{{ $error }}&lt;/li&gt;
@endforeach
&lt;/ul&gt;
&lt;/div&gt;
@endif
&lt;!-- Errors --&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;modal-footer&quot;&gt;
&lt;button class=&quot;btn ripple btn-primary&quot; type=&quot;submit&quot;&gt;save&lt;/button&gt;
&lt;button class=&quot;btn ripple btn-secondary&quot; data-dismiss=&quot;modal&quot; type=&quot;button&quot;&gt;cancel&lt;/button&gt;
&lt;/div&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

and the controller:

public function store(Request $request)
{
$validatedData = $request-&gt;validate(
[
&#39;CurrencyName&#39; =&gt; [&#39;unique:tblcurrencies&#39;, &#39;max:50&#39;]
],
[
&#39;CurrencyName.unique&#39; =&gt; &#39;err1!&#39;,
&#39;CurrencyName.max&#39; =&gt; &#39;err2!&#39;
]
);
Currency::create(
[
&#39;CurrencyRef&#39; =&gt; Helper::GetNewRef(),
&#39;CurrencyName&#39; =&gt; $request[&#39;CurrencyName&#39;],
&#39;CurrencyPrice1&#39; =&gt; $request[&#39;txtcurrencyprice1&#39;],
&#39;CurrencyPrice2&#39; =&gt; $request[&#39;txtcurrencyprice2&#39;],
&#39;CurrentUser&#39; =&gt; auth()-&gt;id()
]
);
return redirect()-&gt;back();
}

what I need is when I click on Save button (if there are any errors I want to display the alert in the modal form without closing the modal form)

答案1

得分: 0

实际上,这个问题在这里待了10天,没有任何答案!我是网页开发新手,但我尝试了很多解决方案,最终成功了。

$(document).ready(function() {
    $('#xform').on('submit', function(e) {
        e.preventDefault();
        var formData = $(this).serialize();

        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: formData,
            success: function(response) {
                location.reload();
            },                
            error: function(xhr, status, error) {
                var errors = xhr.responseJSON.errors;
                if (errors) {
                    $('#errs').empty();
                    $.each(errors, function(key, value) {
                        $('#errs').append('<li>' + value + '</li>');
                    });
                    $('#errs').show();

                    if (!$('#modaldemo8').hasClass('show')) {
                        $('#modaldemo8').modal('show');
                    }
                }
            },
        });
    });
});
英文:

actually, that question was here for 10 days without any answer! I am new in web development but I tried many solutions and finally I got it.

$(document).ready(function() {
$(&#39;#xform&#39;).on(&#39;submit&#39;, function(e) {
e.preventDefault(); 
var formData = $(this).serialize(); 
$.ajax({
url: $(this).attr(&#39;action&#39;),
type: &#39;POST&#39;,
data: formData,
success: function(response) {
location.reload(); 
},                
error: function(xhr, status, error) {
var errors = xhr.responseJSON.errors;
if (errors) {
$(&#39;#errs&#39;).empty();
$.each(errors, function(key, value) {
$(&#39;#errs&#39;).append(&#39;&lt;li&gt;&#39; + value + &#39;&lt;/li&gt;&#39;);
});
$(&#39;#errs&#39;).show();
if (!$(&#39;#modaldemo8&#39;).hasClass(&#39;show&#39;)) {
$(&#39;#modaldemo8&#39;).modal(&#39;show&#39;);
}
}
},
});
});
});

and you should delete the following part:

		&lt;!-- Errors --&gt;
@if ($errors-&gt;any())
&lt;div class=&quot;alert alert-danger&quot;&gt;
&lt;ul&gt;
@foreach ($errors-&gt;all() as $error)
&lt;li&gt;{{ $error }}&lt;/li&gt;
@endforeach
&lt;/ul&gt;
&lt;/div&gt;
@endif
&lt;!-- Errors --&gt;

huangapple
  • 本文由 发表于 2023年6月26日 05:16:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76552441.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定