rjruiz
4 months ago
803
4
Laravel

Validate dynamic fields with FromRequest in laravel

Posted 4 months ago by rjruiz

I am using a fromrequest file to validate each field of my form, I can observe the errors of those fields that are not dynamic, For those fields that if they are directly dynamic does not show the error, it is rare because if I am validating it as a required field in my fromrequest file.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class SavePieceRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = [             

            'denomination' => 'required',
            'code' => 'required',           
            'part_piece' => 'required',
            'number_gag' => 'required',          
            'number_program' => 'required',         
            'time' => 'required',         

        ];

        if($this->request->get('addmore')){
            foreach($this->request->get('addmore') as $key => $val)
            {
                $rules['position.'.$key] = 'required';
                $rules['code_tool.'.$key] = 'required';
                $rules['code_insert.'.$key] = 'required';
                $rules['quality.'.$key] = 'required';
            }
        }

        return $rules;

    }
}

This is how I show the errors that my form fields have, but the fields that are dynamic that I add through jquery and that have errors I cannot visualize.

script:


$('#modal-btn-save').click(function (event) {
    event.preventDefault();

    var form = $('#modal-body form'),
        url = form.attr('action'),
        method = $('input[name=_method]').val() == undefined ? 'POST' : 'PUT';        

    form.find('.help-block').remove();
    form.find('.form-group').removeClass('has-error');

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
    });

    $.ajax({
        url : url,
        method: method,
        data : form.serialize(),
        success: function (response) { 
            form.trigger('reset');
            $('#modal').modal('hide');
            $('#datatable').DataTable().ajax.reload();       

            swal({
                type : 'success',
                title : '¡Éxito!',
                text : '¡Se han guardado los datos!'
            });
        },
        error : function (xhr) {
            var res = xhr.responseJSON;
            if ($.isEmptyObject(res) == false) {
                $.each(res.errors, function (key, value) {
                    $('#' + key)
                        .closest('.form-group')
                        .addClass('has-error')
                        .append('<span class="help-block"><strong>' + value + '</strong></span>');

                });
            }
        }
    })


});

I've realized that I need one (div class = "form-group") for each dynamic field to show the error message, because that's what my script requires, that's how my script shows the error of the fields that make up my form :

error : function (xhr) {
            var res = xhr.responseJSON;
            if ($.isEmptyObject(res) == false) {
                $.each(res.errors, function (key, value) {
                    $('#' + key)
                        .closest('.form-group')
                        .addClass('has-error')
                        .append('<span class="help-block"><strong>' + value + '</strong></span>');

                });
            }

but even so I cannot visualize the error message on my form for fields that are dynamic, I am trying the following within my dynamic table:

Part of my formb (tools section)

    <tbody>
                        @forelse ($piece->tools as $p)  
                        <tr> 

                            <input name="addmore[{{$loop->index}}][insert_id]" value="{{ $p->insert->id }}" hidden/>                       
                            <input name="addmore[{{$loop->index}}][tool_id]" value="{{ $p->id }}" hidden/> 
                            <td>
                                <div class="form-group">
                                    <input type="text" name="addmore[{{$loop->index}}][position]" value="{{ $p->position }}" placeholder="Posición" class="form-control"/>
                                </div>
                            </td>

In the same way I have a (div class = "form-group") in my script that allows me to add the dynamic field in this case to the position field

$("#dynamicTable").append( 
        '<tr>' +           
            '<td>' +
                '<div class="form-group">' + 
                    '<input type="text" name="addmore['+i+'][position]" placeholder="Posicion" class="form-control"/>' +
                '</div>' + 
            '</td>' +
            '<td><input type="text" name="addmore['+i+'][code_tool]" placeholder="Herramienta" class="form-control" /></td>' + 

Please sign in or create an account to participate in this conversation.