Validate modal window using $ this-validate in laravel?

0

Cordial greeting colleagues, I have a form in which I use two modal windows, one to create agents and another to edit them, in my controller I use $ this-> validate, to validate the fields of the form, the problem that I present is that when there is a validation error in the forms, the $ this- > validate redirects me back to the view but with the closed modal window, the idea is that when there is an error, I redirect to the view but with the modal open to visualize the error. How can I do this ?, taking into account that if there is an error in the modal to create it must redirect to the view with the modal to create open and if there is an error in the modal of editing, it must redirect to the view with the respective one modal to edit open to visualize the errors, for now I have this conditional in the blade view:

 {{-- Con este condicional abrimos el modal si hay un error de validacion en el backend --}} 
        @if($errors->any())
            <script>

             $('#createagent').modal('show');

            </script>
        @endif 

But this is not very good, because when any validation error occurs, it will always open the modal to create. I have attached the controller code and the blade view:

driver:

    <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Agent;
use App\User;
use Illuminate\Support\Facades\Auth;

class AgentController extends Controller
{
    public function store(Request $request)
    {


            $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email|unique:agents,email',
            'password' => 'required|min:6'

        ]);




        toastr()->success('Correctamente', 'Agente 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 agente en la bd
        auth()->user()->agent()->create($request->all());

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



    public function show()
    {


        //Con esto obtenemos todos los agentes que pertenezcan a la agencia autenticada
        $agent = Auth::user()->agent()->get();

        return view('AgentList', compact('agent'));
    }

    public function update(Request $request, Agent $agent)
    {
        //Consultamos el email perteneciente al agente
        $email = $agent->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:agents'
        ]);

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

            $agent->fill($request->all());
            $agent->save();





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

    public function destroy(Agent $agent)
    {
        toastr()->error('Correctamente', 'Agente eliminado', [
            'timeOut' => 2000,
            'positionClass' => "toast-top-full-width",
            'progressBar' => false,
            'showDuration'=> 300,
            ]);

        $agent->delete();

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

    public function assign(Agent $agent)
    {

    //Con esto obtenemos todos los clientes que pertenezcan a la agencia autenticada
        $client = Auth::user()->client()->get();

        //Obtenemos los clientes que ya estan asignados al agente
        $clients = $agent->clients;

        return view('AssignClients', compact('agent', 'client', 'clients'));
    }

    public function saveclient(Request $request, Agent $agent)
    {
        toastr()->success('Correctamente', 'Cliente asignado correctamente', [
            'timeOut' => 2000,
            'positionClass' => "toast-top-full-width",
            'progressBar' => false,
            'showDuration'=> 300,
            ]);

        //El metodo attach guarda los datos en la tabla pivote, pero permite la duplicidad de datos
        // $agent->clients()->attach($request->clients);

        //El metodo syncWithoutDetaching evita la duplicidad de datos en la tabla pivote
        $agent->clients()->syncWithoutDetaching($request->clients);



        return redirect()->route('assign.client', $agent);
    }

    public function detachClient(Request $request, Agent $agent, $client)
    {
        toastr()->error('Correctamente', 'Cliente desvinculado', [
            'timeOut' => 2000,
            'positionClass' => "toast-top-full-width",
            'progressBar' => false,
            'showDuration'=> 300,
            ]);

        $agent->clients()->detach($client);

        return redirect()->route('assign.client', $agent);
    }
}

blade view:

 @extends('layouts.app') 

 @section('content')


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

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

</div>
<br>
<div class="container-fluid">
    <!-- Modal para agregar agente -->
    <form action="{{ route('agent.create') }}" method="POST">
        {{ csrf_field() }}
        <div class="modal fade" id="createagent" 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 agente</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 agente</strong></span>
                            <input type="text" class="form-control" name="name" id="name" value="{{ old('name') }}" placeholder="Ingrese el nombre del agente" required><br> {{ $errors->first('name') }}

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

                            <span class="input-group-text"><strong>Contraseña del agente</strong></span>
                            <input type="password" class="form-control" name="password" id="password" placeholder="Ingrese la contraseña del agente" required><br> {{ $errors->first('password') }}



                        </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">CONTRASEÑA</th>
                    <th scope="col">ACCIONES</th>



                </tr>
            </thead>
            <tbody>
                @foreach($agent as $agente)
                <tr>

                    <td>{{ $agente->name }}</td>
                    <td>{{ $agente->email }}</td>
                    <td>{{ $agente->password }}</td>
                    <td>
                        <a href="{{ route('assign.client',$agente->id) }}"> <button class="btn btn-success">Asignar clientes</button> </a>

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

                        <!-- Modal para editar agente -->
                        <div class="modal fade" id="editar_{{$agente->id}}" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
                            <div class="modal-dialog" role="document">
                                <form action="{{ route('agent.update',$agente->id) }}" method="POST">
                                {{ csrf_field() }} {{ method_field('PUT') }}
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h4 class="modal-title" id="modalLabel">Editar agente</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="{{ $agente->id }}" hidden>

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

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

                                                <span class="input-group-text"><strong>Contraseña del agente</strong></span>
                                                <input type="password" class="form-control" name="password" id="password" value="{{ $agente->password }}" placeholder="Ingrese la contraseña del agente" required><br> {{ $errors->first('password') }}



                                        </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('agent.destroy', $agente->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 agente?')">
                                <i class="fa fa-times"></i></button>
                        </form>
                    </td>
                </tr>
                @endforeach
            </tbody>
        </table>
        {{-- Con este condicional abrimos el modal si hay un error de validacion en el backend --}} 
        @if($errors->any())
            <script>

             $('#createagent').modal('show');

            </script>
        @endif 


    </div>


@stop

Any idea of how I can solve this? Is it possible to return a specific value when the $ this validate finds an error ?, in this way use a value that differentiates, if the error comes from the function create or edit and so use a conditional in the blade view to open the specific modal?.

    
asked by Kevin Burbano 21.06.2018 в 18:00
source

1 answer

1

good day what you want is a crud with ajax and modal, the good thing is that I have a good example in the following link, I can not publish all the code for being long, but I will pass a project you need, the advantage is that I only need to use one form instead of two
link

configure the bontones to save the data

<button class="mass_show-modal btn btn-danger"
        data-id="{{ $lists->id}}"
        data-nombre="{{ $lists->nombre}}"
        data-comuna_id="{{ $lists->comuna_id}}"
        data-municipios_id="{{ $lists->municipios_id}}"
        data-created_at="{{ $lists->created_at}}"
        data-updated_at="{{ $lists->updated_at}}"
><span class="glyphicon glyphicon-trash"></span>Eliminar</button>

at this point you get the field data

$(document).on('click', '.mass_show-modal', function() {
            $('.modal-descripcion').text('Vista de los Datos');
            $('#msdelete').text(' ');

            $('#id_mass').val($(this).data('id'));
$('#nombre_mass').val($(this).data('nombre'));
$('#comuna_id_mass').val($(this).data('comuna_id'));
$('#municipios_id_mass').val($(this).data('municipios_id'));
$('#created_at_mass').val($(this).data('created_at'));
$('#updated_at_mass').val($(this).data('updated_at'));
;


            $('#massModal').modal('show');
            $('#acciones').attr('class', 'btn btn-info hibe');
            $('#acciones').text('Visible');
            $('#acciones').attr('disabled');

        });

and the following property is used in the modal

<div id="massModal" class="modal fade" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-descripcion"></h4>
                </div>
            </div>
        </div>
</div>
    
answered by 21.06.2018 / 22:06
source