"Solve the problem that select2 cannot select data"
P粉604848588
P粉604848588 2024-02-26 08:40:27
0
1
437

When editing data, my select2 has a small problem, select2 will not select the value This is my data display table data

When I click the "Edit Data" button it should select "Settings" on the parent value but it is not working, see this

Modal script

<div class="modal fade" id="modal-edit" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title mt-0">Edit Data Navigation</h5>
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        </div>
        <div class="modal-body">
            <input type="hidden" id="token" value="{{ csrf_token() }}">
            <input type="hidden" id="nav_id">
            <div class="form-group">
                <label>Nama Menu</label>
                <input type="text" name="name" class="form-control name" id="name"
                    placeholder="Type something" />
                <div class="alert alert-danger mt-2 d-none" role="alert" id="alert-name"></div>
            </div>
            <div class="form-group">
                <label>URL</label>
                <input type="text" name="url" class="form-control url" id="url"
                    placeholder="Type something" />
                <div class="alert alert-danger mt-2 d-none" role="alert" id="alert-url"></div>
            </div>
            <div class="form-group">
                <label>Icon</label>
                <input type="text" name="icon" class="form-control icon" id="icon"
                    placeholder="Type something" />
                <div class="alert alert-danger mt-2 d-none" role="alert" id="alert-icon"></div>
            </div>
            <div class="form-group">
                <label>Parent</label>
                <select id="parent_id" class="form-control parent_id">
                    <option value=""></option>
                </select>
                <div class="alert alert-danger mt-2 d-none" role="alert" id="alert-parent"></div>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">TUTUP</button>
            <button type="button" class="btn btn-primary" id="update">SIMPAN</button>
        </div>
    </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->

This is my ajax script

Ajax script

// select2 data parents
$(document).ready(function() {
    var _token = $('meta[name="csrf-token"]').attr('content');
    var parentSelect = $('.parent_id');
    $(".parent_id").select2({
        dropdownParent: $('#modal-edit'),
        placeholder: 'Choose Parent',
        ajax: {
            url: "{{ route('getNavigations') }}",
            type: "get",
            dataType: 'json',
            delay: 250,
            data: function(params) {
                return {
                    token: _token,
                    search: params.term // search term
                };
            },
            processResults: function(response) {
                return {
                    results: response
                };
            },
            cache: true
        }
    });
});

Getting data when edit button is clicked I usually use trigger to set selected value of select2 but it doesn't work

retrieve data

$('body').on('click', '#btn-edit-post', function() {
    var nav_id = $(this).data('id');
    //fetch detail post with ajax
    $.ajax({
        url: `navigations/${nav_id}`,
        type: "GET",
        cache: false,
        success: function(response) {
            // console.log(response);
            //fill data to form
            $('#nav_id').val(response.data.id);
            $('.name').val(response.data.name);
            $('.url').val(response.data.url);
            $('.icon').val(response.data.icon);
            $('.parent_id').val(response.data.parent_id).trigger('change');
            //open modal
            $('#modal-edit').modal('show');
        }
    });
});

This is my controller

Controller

public function getNavigations(Request $request)
{
    $search = $request->search;
    if ($search == '') {
        $navigation = Navigation::orderby('name', 'asc')->select('id', 'name', 'parent_id')->where('parent_id')->limit(5)->get();
    } else {
        $navigation = Navigation::orderby('name', 'asc')->select('id', 'name', 'parent_id')->where('name', 'like', '%' . $search . '%')->limit(5)->get();
    }
    // create respons
    $response = array();
    foreach ($navigation as $parent) {
        $response[] = array(
            "id"        => $parent->id,
            "text"      => $parent->name,
        );
    }
    // dd($response);
    return response()->json($response);
}

The data is displayed but not selected, it should be like this

I don't know if the way I am writing the code is correct, I am new to coding so please help me :)

P粉604848588
P粉604848588

reply all(1)
P粉727531237

So I found the solution with the code I created. I've added some code in the controller and my JavaScript script. Here is the code I added:

In the controller, to get the data, I added the following code:

// Get all parent navigation items (excluding the current navigation item)
    $parentItems = Navigation::where('id', '!=', $id)->get(['id', 'name']);

This is the completed part of the code Click here to view

As for the JavaScript, I made some changes to the return value of select2 as follows:

/// Get the name of the parent item based on parent_id
            var parentName = '';
            var parentItem = response.parent_items.find(function(item) {
                return item.id === response.data.parent_id;
            });
            if (parentItem) {
                parentName = parentItem.name;
            }
            var newOption = new Option(parentName, response.data.parent_id, true, true);
            $(".parent_id").append(newOption).trigger('change');

This is the completed part of the code Click here to view

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template