简体   繁体   English

如何滚动到 livewire laravel 中的第一个验证错误消息

[英]how to scroll to first validation error message in livewire laravel

I am new in livewire.我是livewire的新手。 i am working on registration process of user.我正在处理用户的注册过程。 Register form is quite big and validations also working fine to me.注册表非常大,验证对我来说也很好。 The problem is when user submits the form validations came but user not able to see because submit button is at bottom and form is at top.问题是当用户提交表单验证时,用户无法看到,因为提交按钮位于底部而表单位于顶部。

When i manually scroll to top error message is displaying.当我手动滚动到顶部时,正在显示错误消息。 So what i want when user submits the form its will automatically go to first error message.所以当用户提交表单时我想要的是它会自动 go 到第一条错误消息。 Here is my code:这是我的代码:

<form wire:submit.prevent="userRegister">
<div class="row">
    <div class="col-md-3">
        <label>First Name *</label>
    </div>
    <div class="col-md-9">
        <input type="text" wire:model="register.first_name" placeholder="Enter First Name" required>
        @error('register.first_name') <span class="text-danger">{{ $message }}</span> @enderror
    </div>
</div>
<div class="row">
    <div class="col-md-3">
        <label>Last Name *</label>
    </div>
    <div class="col-md-9">
        <input type="text" wire:model="register.last_name" placeholder="Enter Last Name">
        @error('register.last_name') <span class="text-danger">{{ $message }}</span> @enderror
    </div>
</div>
<div class="row">
    <div class="col-md-3">
        <label>Test 1 Name *</label>
    </div>
    <div class="col-md-9">
        <input type="text" wire:model="register.test1_name" placeholder="Enter Last Name">
    </div>
</div>
<div class="row">
    <div class="col-md-3">
        <label>Test 2 Name *</label>
    </div>
    <div class="col-md-9">
        <input type="text" wire:model="register.test2_name" placeholder="Enter Last Name">
    </div>
</div>
<div class="row">
    <div class="col-md-3">
        <label>Test 3 Name *</label>
    </div>
    <div class="col-md-9">
        <input type="text" wire:model="register.test3_name" placeholder="Enter Last Name">
    </div>
</div>
<div class="row">
    <div class="col-md-3"></div>
    <div class="col-md-9">
        <!--<input type="submit" value="Edit" class="edt-sb">-->
        <input wire:click="userRegister" type="submit" value="Submit" class="edt-sv">
    </div>
</div>
</form>

My Register.php我的寄存器.php

<?php

namespace App\Http\Livewire;

use Livewire\Component;
class Register extends Component
{
public $register;
protected $rules = [
    'register.first_name' => 'bail|required|max:50',
    'register.last_name' => 'bail|required|max:50',
];

protected $messages = [
    'register.first_name.required' => 'Please enter first name',
];

public function userRegister(){
    $this->validate();
}

I want when user submits the form it will immediately scroll to first error message.我希望当用户提交表单时,它会立即滚动到第一条错误消息。 Currently my validations work perfects for me.目前我的验证工作对我来说很完美。 Do i need to use alpine js?我需要使用高山js吗? for this.为了这。

Livewire errors will be saved in $errors bag so probably you can add an id to each field in your form and use alpinejs to focus the first element with the id present in the errors bag, something like: Livewire 错误将保存在 $errors 包中,因此您可能可以为表单中的每个字段添加一个 id,并使用 alpinejs 将第一个元素与错误包中存在的 id 放在一起,例如:

        <div x-data="{
                'errors': {{ json_encode(array_keys($errors->getMessages())) }},
                focusField(input) {
                    fieldError = document.getElementById(input);
                    if (fieldError) {
                        fieldError.focus({preventScroll:false});
                    }
                },
            }"
             x-init="() => { $watch('errors', value => focusField(value[0])) }">
            
                    <input id="register.test3_name" type="text" wire:model="register.test3_name" placeholder="Enter Last Name">
        </div>

I nearly faced the same issue but with success message not error messages, for error messages I used updated() , they are shown on real time for user while filling the fields.我几乎遇到了同样的问题,但是成功消息不是错误消息,对于我使用updated()的错误消息,它们会在用户填写字段时实时显示。

My Class Component:我的 Class 组件:

class FormSubmissions extends Component
{
    public $city;
    public $fullname;

    protected $rules = [
        'city' => 'required',
        'fullname' => 'required',
    ];

    public $successMessage;

    public function updated($propertyName)
    {
        $this->validateOnly($propertyName);
    }

    public function submitForm()
    {
        $submission = $this->validate();



        $this->successMessage = trans('site.success');


        $this->resetForm();
    }


    public function resetForm()
    {
        $this->city = '';
        $this->fullname = '';
    }

}

My Blade template:我的刀片模板:

<div id="formSection" class="form-wrapper">
    @if ($successMessage)
        <div  class="alert alert-success alert-dismissible fade show" role="alert">
            {{ $successMessage }}
            <button  wire:click="$set('successMessage', null)" type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <script>
            var elmnt = document.getElementById("formSection");
            elmnt.scrollIntoView();
        </script>
    @endif
    <form wire:submit.prevent="submitForm" action="/" method="POST">
    ...

</div>

So the small script added with success message allowed me to scroll back to top of my form Section #formSection .因此,添加成功消息的小脚本允许我滚动回表单 Section #formSection的顶部。

If you are using <x-jet-input-error/> component for displaying errors, you can just modify resources/views/vendor/jetstream/components/input-error.blade.php (make sure you have published livewire views) file to below code:如果您使用<x-jet-input-error/>组件来显示错误,您只需修改resources/views/vendor/jetstream/components/input-error.blade.php (确保您已发布 livewire 视图)文件到下面的代码:

@props(['for'])

<span x-data="{hasError: '{{$errors->get($for)[0] ?? ''}}' }"
     x-init="()=> { $watch('hasError', (value)=> {
            let errorDiv = document.getElementsByClassName('invalid-feedback')[0];
            if(errorDiv){
                errorDiv.scrollIntoView({behavior: 'smooth', block: 'center', inline: 'nearest'});
            }
    })}">
    @error($for)
        <span {{ $attributes->merge(['class' => 'invalid-feedback d-block']) }} role="alert" style="font-size: inherit">
            <strong>{{ $message }}</strong>
        </span>
    @enderror
</span>

Explanation : we use alpine to watch for changes in the validation message for the "$for" field.解释:我们使用 alpine 来观察“$for”字段的验证消息的变化。 As soon as it changes (validation message shows up or vanishes), it looks for the error block and scrolls to it一旦它发生变化(验证消息显示或消失),它就会查找错误块并滚动到它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM