After laravel validation fails, choose a select option

0

Hello everyone, I have two combos: one states and one cities.

When I choose a state, I search cities via ajax, as follows:

$('#estados').on('change', function(e){
    console.log(e);
    var id = e.target.value;

    /* busca as cidades de um determinado estado */
    $.get("{{ url('/administrador/buscar-cidades') }}/" + id, function(data) {
        //esvazia as cidades anteriores 
        $('#cidades').empty();
        $.each(data, function(index,subCatObj){
            //console.log(subCatObj);
            var option = new Option(subCatObj.nome, subCatObj.id);
            $(option).html(subCatObj.nome);
            $('#cidades').append(option);
        });
    });
});

This works perfectly. However, I'm using laravel as a backend and I have a validation in the controller. If the validation fails, I'm going back to the previous page with the id of the city and I want the city to be chosen again.

Here's the check:

if ($validator->fails()) {
   return redirect()->back()->withErrors($validator)->withInput()->with('idCidade', $request->input('cidade_id'));
}

For this, I added the following javascript to reload the states:

$(document).ready(function() {
    if ($("#estados").find('option:selected').val() != "--Selecione--") {
        $("#estados").trigger('change');
    }
});

What this does is basically do the load of the cities again if the validation fails, to fill the cities. And it works.

The problem now is that I was able to get the ID of the city that had been previously chosen, which was passed from the controller to the view, and choose the correct city (which had already been chosen before the verification).

How to do this?

    
asked by anonymous 21.12.2017 / 22:37

1 answer

1

Create a localStorage with the city code in the front-end as soon as you choose a city in select :

$('#cidades').on('change', function(){
    localStorage.cidade = $(this).val();
});

In Ajax that loads states, pull localStorage if it is of any value:

$('#estados').on('change', function(e){
    console.log(e);
    var id = e.target.value;

    /* busca as cidades de um determinado estado */
    $.get("{{ url('/administrador/buscar-cidades') }}/" + id, function(data) {
        //esvazia as cidades anteriores 
        $('#cidades').empty();
        $.each(data, function(index,subCatObj){
            //console.log(subCatObj);
            var option = new Option(subCatObj.nome, subCatObj.id);
            $(option).html(subCatObj.nome);
            $('#cidades').append(option);
            if(localStorage.getItem("cidade") !== null){
                $('#cidades').val(localStorage.cidade);
            }
        });
    });
});

Do not forget to delete localStorage when you no longer need it:

localStorage.removeItem('cidade');
    
22.12.2017 / 01:12