Validate modal window when there is an error in Laravel?

1

Cordial regards colleagues, it turns out that I am developing an application in laravel that so far allows me to perform a full crud of clients, to create and edit clients I use bootstrap and jquery modal windows, the problem that I present is that in the controller I use the $ this- > validate, to do the respective validations of the form that is in the modal windows, when an error occurs in the data entry the $ this- > validate me returns to the same view and it shows me the error in the form, but in this case, I'm using modal windows I had to make a conditional in the blade view, so that when a validation error occurs I will return to the same view and open the modal to visualize the error, this validation is the following:

{{-- Con este condicional abrimos el modal si hay un error de validacion en el backend --}}
     @if($errors->any())
    <script>
        $('#createclient').modal('show');
    </script>
    @endif

The problem is that it is only working with the modal to create a client. How could I validate that, when there is an error in the form to create, I return to the view with the modal to create open and when there is an error in the form to edit I return to the view with the modal of editing open?

I attached the complete blade view code:

@extends('layouts.app')
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>


@section('content')


<div class="container" style="text-align:right">

    <button type="button" class="btn btn-success" data-toggle="modal" data-target="#createclient">
        Añadir cliente
    </button>

</div>
<br>

<div class="container-fluid">
    <!-- Modal para agregar cliente -->
    <form action="{{ route('client.create') }}" method="POST">
            {{ csrf_field() }}
    <div class="modal fade" id="createclient" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title" id="modalLabel">Crear cliente</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>

                <div class="modal-content">
                    <div class="container-fluid">                      

                            <span class="input-group-text">
                                <strong>Nombre del cliente</strong>
                            </span>
                            <input type="text" class="form-control" name="name" id="name" value="{{ old('name') }}" placeholder="Ingrese el nombre del cliente" required>
                            <br> {{ $errors->first('name') }}

                            <span class="input-group-text">
                                <strong>Correo del cliente</strong>
                            </span>
                            <input type="email" class="form-control" name="email" id="email" value="{{ old('email') }}" placeholder="Ingrese el correo del cliente" required>
                            <br> {{ $errors->first('email') }}
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Crear</button>
                </div>


            </div>

        </div>
    </div>
    </form>
</div>
    <div class="container-fluid">



        <table class="table table-hover table-striped">
            <thead class="thead-dark">
                <tr>

                    <th scope="col">NOMBRE</th>
                    <th scope="col">CORREO</th>
                    <th scope="col">Acciones</th>


                </tr>
            </thead>
            <tbody>
                @foreach($client as $cliente)
                <tr>

                    <td>{{ $cliente->name }}</td>
                    <td>{{ $cliente->email }}</td>
                    <td>

                        <button type="button" data-id="{{ $cliente->id }}" class="btn btn-primary" data-toggle="modal" data-target="#editar_{{$cliente->id}}">
                            <i class="fa fa-edit"></i>
                        </button>

                        <!-- Modal para editar cliente -->
                        <div class="modal fade" id="editar_{{$cliente->id}}" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
                            <div class="modal-dialog" role="document">
                                <form action="{{ route('client.update',$cliente->id) }}" method="POST">
                                    {{ csrf_field() }} {{ method_field('PUT') }}
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h4 class="modal-title" id="modalLabel">Editar cliente</h4>
                                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                        </div>
                                        <div class="modal-content">
                                            <div class="container-fluid">

                                                <input type="text" name="id" value="{{ $cliente->id }}" hidden>
                                                <span class="input-group-text">
                                                    <strong>Nombre del cliente</strong>
                                                </span>
                                                <input type="text" class="form-control" name="name" id="name" value="{{ $cliente->name }}" placeholder="Ingrese el nombre del cliente" required>
                                                <br> {{ $errors->first('name') }}

                                                <span class="input-group-text">
                                                    <strong>Correo del cliente</strong>
                                                </span>
                                                <input type="email" class="form-control" name="email" id="email" value="{{ $cliente->email }}" placeholder="Ingrese el correo del cliente" required>
                                                <br> {{ $errors->first('email') }}
                                                <input type="text" name="user_id" value="{{ auth()->user()->id }}" hidden>

                                            </div>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="submit" class="btn btn-primary">Editar</button>


                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>

                        {{-- boton para eliminar --}}
                        <form method="POST" action="{{ route('client.destroy', $cliente->id) }}" style="display:inline">

                            {{ csrf_field() }} {{ method_field('DELETE') }}

                            <button class="btn btn-xs btn-danger" onclick="return confirm('¿Estas seguro de querer eliminar este cliente?')">
                                <i class="fa fa-times"></i>
                            </button>


                        </form>



                    </td>


                </tr>
                @endforeach
            </tbody>
        </table>


    </div>
    {{-- Con este condicional abrimos el modal si hay un error de validacion en el backend --}}
     @if($errors->any())
    <script>
        $('#createclient').modal('show');
    </script>
    @endif 
    @stop

I also attach the functions of creating and editing the controller just in case:

store function to create:

  public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email|unique:clients,email'

         ]);

        toastr()->success('Correctamente', 'Cliente creado', [
            'timeOut' => 2000,
            'positionClass' => "toast-top-full-width",
            'progressBar' => false,
            'showDuration'=> 300,
            ]);

        //De esta forma se inserta tambien el id del usuario al que pertenece el cliente en la bd
        auth()->user()->client()->create($request->all());

        return redirect()->route('client.list');
    }

update function to update or edit the client:

  public function update(Request $request, Client $client)
    {
        //Consultamos el email perteneciente al cliente
        $email = $client->email;

        //Si el email que llega por request, es igual al de la base de datos
        if ($request->email == $email) {
            $request->request->remove('email');
        }


        $this->validate($request, [
            'email' => 'unique:clients'
        ]);

        toastr()->info('Correctamente', 'Cliente editado', [
            'timeOut' => 2000,
            'positionClass' => "toast-top-full-width",
            'progressBar' => false,
            'showDuration'=> 300,
            ]);


        return redirect()->route('client.list');
    }
    
asked by Kevin Burbano 20.06.2018 в 02:34
source

1 answer

0

I have an example and I hope it works for you: this is a field that I am doing dentron modal with the modal

 <div class='form-group' id='descripcion' >
        <label class='control-label col-sm-2' for='descripcion'>descripcion:</label>
           <div class='col-sm-10'>
               <input type='text' class='form-control' id='descripcion_mass' maxlength='45'   required='required' autofocus>
                    <p class='errornombre text-center alert alert-danger hidden'></p>
           </div>
</div>

in the js file the request is made in ajax in the pair

  success: function(data) { 
            $('.errorid').addClass('hidden');$('.errornombre').addClass('hidden');$('.errormunicipios_id').addClass('hidden');$('.errorcreated_at').addClass('hidden');$('.errorupdated_at').addClass('hidden');;
            if ((data.errors)) {
                    //setTimeout(function () {      
                        $('#massModal').modal('show');
                    //  toastr.error('Validation error!', 'Error Alert', {timeOut: 5000});
                    //}, 500);
            if(data.errors.id){$('.errorid').removeClass('hidden');$('.errorid').text(data.errors.id);
            }
            if(data.errors.nombre){$('.errornombre').removeClass('hidden');$('.errornombre').text(data.errors.nombre);
            }
        } else {
            Alert("si paso");
            toastr.success('Successfully added Post!', 'Success Alert', {timeOut: 5000});

        }
    }

I have it in the controller in the following way

public function __construct()
    {
        $this->middleware('auth');



    }
    /**
    * @var array
    */
    protected $rules =
    [

                //'id' => 'required|min:1|max:99999999',
                'consecutivo' => 'required|min:1|max:99999999',
                'asistencias_estado_id' => 'required|min:1|max:99999999',
                'barrio_id' => 'required|min:1|max:99999999',
                'usuario_id' => 'required|min:1|max:99999999',
                'vereda' => 'required|min:2|max:255|regex:/^([0-9a-zA-ZñÑáéíóúÁÉÍÓÚ_-])+((\s*)+([0-9a-zA-ZñÑáéíóúÁÉÍÓÚ_-]*)*)+$/',
                'telefono' => 'required|min:1|max:99999999',
                'concepto' => 'required|min:2|max:255|regex:/^([0-9a-zA-ZñÑáéíóúÁÉÍÓÚ_-])+((\s*)+([0-9a-zA-ZñÑáéíóúÁÉÍÓÚ_-]*)*)+$/',
                'agricola' => 'required|min:2|max:255|regex:/^([0-9a-zA-ZñÑáéíóúÁÉÍÓÚ_-])+((\s*)+([0-9a-zA-ZñÑáéíóúÁÉÍÓÚ_-]*)*)+$/',
                'pecuaria' => 'required|min:2|max:255|regex:/^([0-9a-zA-ZñÑáéíóúÁÉÍÓÚ_-])+((\s*)+([0-9a-zA-ZñÑáéíóúÁÉÍÓÚ_-]*)*)+$/',
                'forestal' => 'required|min:2|max:255|regex:/^([0-9a-zA-ZñÑáéíóúÁÉÍÓÚ_-])+((\s*)+([0-9a-zA-ZñÑáéíóúÁÉÍÓÚ_-]*)*)+$/',
                'ambiental' => 'required|min:2|max:255|regex:/^([0-9a-zA-ZñÑáéíóúÁÉÍÓÚ_-])+((\s*)+([0-9a-zA-ZñÑáéíóúÁÉÍÓÚ_-]*)*)+$/',
                'dianosticos' => 'required|min:2|max:255|regex:/^([0-9a-zA-ZñÑáéíóúÁÉÍÓÚ_-])+((\s*)+([0-9a-zA-ZñÑáéíóúÁÉÍÓÚ_-]*)*)+$/',
                'recomendaciones' => 'required|min:2|max:255|regex:/^([0-9a-zA-ZñÑáéíóúÁÉÍÓÚ_-])+((\s*)+([0-9a-zA-ZñÑáéíóúÁÉÍÓÚ_-]*)*)+$/',
                'usuario_umata' => 'required|min:1|max:99999999',

    ];

in a function this way

public function update(Request $request, $id)
    {
        $validator = Validator::make(Input::all(), $this->rules);
        if ($validator->fails()) {
            return Response::json(array('errors' => $validator->getMessageBag()->toArray()));
        } else {
            $Asistencia = AsistenciaModel::findOrFail($id);

             $Asistencia->consecutivo=$request->consecutivo;
                 $Asistencia->asistencias_estado_id=$request->asistencias_estado_id;
                 $Asistencia->barrio_id=$request->barrio_id;
                 $Asistencia->usuario_id=$request->usuario_id;
                 $Asistencia->vereda=$request->vereda;
                 $Asistencia->telefono=$request->telefono;
                 $Asistencia->concepto=$request->concepto;
                 $Asistencia->agricola=$request->agricola;
                 $Asistencia->pecuaria=$request->pecuaria;
                 $Asistencia->forestal=$request->forestal;
                 $Asistencia->ambiental=$request->ambiental;
                 $Asistencia->dianosticos=$request->dianosticos;
                 $Asistencia->recomendaciones=$request->recomendaciones;
                 $Asistencia->usuario_umata=$request->usuario_umata;
                 $Asistencia->created_at=$request->created_at;
                 $Asistencia->updated_at=$request->updated_at;


            $Asistencia->save();
            return response()->json($Asistencia);
        }
    }
    
answered by 20.06.2018 в 15:45