Calculated Fields

0

Working with laravel 5.5

I have a question, I have these 3 fields:

Start Time:

{!! Form::myInput('time', 'hora_inicio', 'Hora inicio: ', ['required']) !!}

End Time

{!! Form::myInput('time', 'hora_final', 'Hora final: ', ['required']) !!}

Total Time

{!! Form::myInput('text', 'tiempo_total', 'Tiempo Total: ', ['required', 'readonly' => 'readonly']) !!}

I would like to know how to do so that the final time will be subtracted from the initial time, and calculate yourself in the field total_time, to be able to save it in a BD, and obviously, that the initial time is not longer than the final hour .

Thanks for reading.

    
asked by Omar Noa 07.09.2018 в 17:57
source

1 answer

2

If the end user does not use the "total time" data, I would suggest hiding it from the form. To do what you want in PHP you can use the "Carbon" library that is already included in Laravel.

You import the class;

use Carbon\Carbon;

In your role you put the following:

public function unaFuncion(Request $request){
     $hora_inicial = new Carbon($request->hora_inicial);
     $hora_final = new Carbon($request->hora_final);

     $duracion = $hora_final->diff($hora_inicial)->format('%H:%i:%s');  
}

You should make the most of what the framework already brings.

Now that if you want to keep the total time input, you can calculate the difference with javascript (using jQuery and moment.js) in the following way:

$(document).ready(function(){
    calcularTiempo();
});

function calcularTiempo(){
    //Tomando en cuenta que solo hay un input con esos nombres en el formulario
    $('input[name=hora_inicio], input[name=hora_final]').on('change', function(e){
    var valorInicio = $.trim($("input[name=hora_inicio]").val());
    var valorFinal = $.trim($("input[name=hora_final]").val());

    //Comprobar que si haya valores en ambos campos para poder validar y calcular
    if(valorInicio != '' && valorFinal != ''){
       //Validar el formato correcto del tiempo (HH:mm - 22:05)
       if(!validarHMS(valorInicio) || !validarHMS(valorFinal)){
          //alertar al usuario que los datos no son válidos
          return false;
       }
      //crear formato de fecha

      tiempoInicial = moment(valorInicio, "hh:mm");
      tiempoFinal = moment(valorFinal, "hh:mm");

      var total = moment(tiempoFinal.diff(tiempoInicial)).format("hh:mm"); 

      $('#tiempo_total').val(total);
    } 



});

}

function validarHMS(valor) {
        var esValido = /^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?$/.test(valor);

        return esValido;
    }

If I strongly recommend the addition of the moment.js library for handling issues of dates and times, it makes things much easier for you.

Similarly, if you keep the total time input in your form, you will have to re-calculate in PHP because anyone could modify the input.

    
answered by 07.09.2018 / 18:45
source