Home > Software engineering >  How to set selected value in edit mode - Select2 with AJAX Remote Data
How to set selected value in edit mode - Select2 with AJAX Remote Data

Time:11-30

Please wait, I know you will say that this is a possible Duplicate. The answer is Yes. Here's the link

But none of the answers works for me.

On my blade I put the value in a hidden input field.

<input type="hidden" value="{{ $recipe->cuisine_type_id }}" id="selectedCuisineTypeId">

I have the same scenarios. Here's my JS;

    var selectedCuisineTypeId = $("#selectedCuisineTypeId").val();
    $('#cuisine_type_id').val(selectedCuisineTypeId).trigger('change');

    $( "#cuisine_type_id" ).select2({
        ajax: {
            headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        placeholder: "Select Cuisine",
        url: "{{ route('ajax-cuisine-search') }}",
        type: "post",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
            search: params.term // search term
            };
        },
        processResults: function (response) {

            return {
                results: response
            };
        },
        cache: true
        }
    });

Why it is not working for me? What did I miss?

CodePudding user response:

I have solved my issue above. Here's what I did.

  1. Make a hidden field of the ID you want to get selected and set a variable for it.

    <input type="hidden" value="{{ $recipe->cuisine_type_id }}" id="selectedCuisineTypeId">

  2. Create a new route to fetch the selected value and trigger Select2.

Route

Route::get('recipe/cuisine/{id}', [SearchController::class, 'getSelectedCuisine'])->name('getSelectedCuisine');

Controller

*selectCuisineSearch class to load the list of Cuisines. getSelectedCuisine class to fetch the selected Cuisine in Edit Mode

    public function selectCuisineSearch(Request $request)
{

    $search = $request->search;

    if ($search == '') {
        $cuisines = Cuisine::orderby('name', 'asc')->select('id', 'name')->get();
    } else {
        $cuisines = Cuisine::orderby('name', 'asc')->select('id', 'name')->where('name', 'like', '%' . $search . '%')->limit(5)->get();
    }

    $response = array();
    foreach ($cuisines as $cuisine) {
        $response[] = array(
            "id" => $cuisine->id,
            "text" => $cuisine->name
        );
    }
    return response()->json($response);
}



    public function getSelectedCuisine(Request $request)
    {
        $cuisineId = $request->id;
        $cuisines = Cuisine::where('id',  $cuisineId)->first();
        $response = array(
            "id" => $cuisines->id,
            "name" => $cuisines->name
        );
        return response()->json($response);
    }

On my Edit Blade

    $(document).ready(function(){
        $( "#cuisine_type_id" ).select2({
        ajax: {
            headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        placeholder: "Select Cuisine",
        url: "{{ route('ajax-cuisine-search') }}",
        type: "post",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                search: params.term
            };
        },
        processResults: function (response) {
            return {
                results: response
            };
        },
        cache: true
        }
    });

    var selectedCuisineTypeId = $("#selectedCuisineTypeId").val();
    var cuisineSetSelected = $('#cuisine_type_id');
    $.ajax({
        type: 'GET',
        url: '{{ route('getSelectedCuisine')/'   selectedCuisineTypeId
    }).then(function (response) {
        var option = new Option(response.name, response.id, true, true);
        cuisineSetSelected.append(option).trigger('change');

        cuisineSetSelected.trigger({
            type: 'select2:select',
            params: {
                results: response
            }
        });
    });
});

This solution might be long. You are free to suggest making this shorter. I am happy to learn more. Cheers!

  • Related