0
votes

I'm trying to select a value into a select box using Select2 and Ajax autocomplete with Laravel and Blade. I have the problem only on edit-mode (when I already have a value on DB) and it works without problme in insert-mode. Here my html code where the select is empty:

<select class="form-control" id="city-name" name="city" style="width: 100%">
    {{ isset($indirizzi->city_id) ? "<option value=\"". $indirizzi->city->id ."\" selected>".$indirizzi->city->name."</option>" : "" }}
</select>

Here my javascript code where I get value from DB and create a new option value:

<script>
    var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');

    @if(isset($indirizzi))
        var newOption = new Option('{{ $indirizzi->city->name }}', '{{ $indirizzi->city->id }}', true, true);
        var txtOption = '<option value="{{ $indirizzi->city->id }}" selected>{{ $indirizzi->city->name }}</option>';
        $('#city-name').append(txtOption).val('{{ $indirizzi->city->id }}');
        $('#city-name').select2().trigger('change');
    @endif

    $().ready(function () {
        $("#city-name").select2({
            ajax: {
                url: "{{ route("ajaxFindCity") }}",
                dataType: 'json',
                delay: 250,
                type: "POST",
                data: function (params) {
                    return {
                        _token: CSRF_TOKEN,
                        city: params.term
                    };
                },
                processResults: function (data) {
                    return {
                        results: data
                    };
                },
                error: function (data) {
                    showException(data);
                },
                cache: true
            },
            minimumInputLength: 3,
            templateSelection: function (data) {
                return data.city;
            }
        });
    });
</script>

But on loadind the page I can see the selected value into my selectbox but doesn't work the search of a new value...

This is the code of function into route("ajaxFindCity") that works if I'm not in edit view:

public function ajaxFind(Request $request)
{
    // Recupero la città da ricercare
    $city = $request->get("city");
    // Recupero le città che rientrano nella mia ricerca
    $cities = City::with('province')->where('cities.name', 'like', $city . '%')->get();
    $result = [];
    foreach ($cities as $city) {
        $result[] = [
            "id" => $city->id,
            "text" => $city->name . " (" . $city->province->code . ")",
            "city" => $city->name,
            "province" => $city->province->code
        ];
    }
    return response()->json($result);
}
1
Do you get any Javascript error? Can you add the code of your route("ajaxFindCity") - Christophe Hubert
If I load the page without getting old value from DB (so I have to choose city for first time), The Select2 works. I added the code of the function you asked me in my question. - Swim89
Thanks for the code - Now you don't need to add an option by JS if you already have the <option value="3620194" selected="selected">select2/select2</option> so you can remove your @if(isset($indirizzi)) condition. - Christophe Hubert
I'll submit an answer just to make my code clearer - Christophe Hubert

1 Answers

1
votes

As seen in the documention for default value (https://select2.org/data-sources/ajax#default-pre-selected-values) You need to remove the extra code:

@if(isset($indirizzi)
  ...
@endif

And replace your select by:

<select class="form-control" id="city-name" name="city" style="width: 100%">
@if($indirizzi)
   <option value="{{ $indirizzi->city_id }}" selected="selected"> {{ $indirizzi->city->name }}</option>
@endif
</select>