How to get select2 text value instead of the id

How to get select2 text value instead of the id

psionicinteractivepsionicinteractive Posts: 1Questions: 1Answers: 0

Hi
I am trying to use select2 on the editor in the "create modal".
In the editor when I am clicking the create button its appending the id of the selected element from the select2 to the table. I need to append the text of the selected element (However I also need the id since I will be submitting the Datatable with all values).

I found a static way to compare the id with hard coded properties and then putting that properties to the table from the following link.

https://editor.datatables.net/examples/simple/fieldTypes.html

But i am looking for a dynamic way to do that.

Answers

  • kthorngrenkthorngren Posts: 21,174Questions: 26Answers: 4,923

    In my environment I return the options in the JSON response as described here:
    https://editor.datatables.net/manual/server#DataTables-parameters

    I use a custom backend which pulls all of the options from the DB and builds the label/value pairs as shown in your above example. Not sure how the options are generated using the Datatables server code.

    The tricky part, at least for me, is to setup the data structure. Here is an example select2 field I have:

    Editor:

                { label: 'Test Cases:', name: 'main.fk_test_cases_list[]',
                        type: 'select2',
                        attr: { multiple: true },
                        opts: { allowClear: true,
                                placeholder: 'Add test cases',
                                //tags: true,
                                tokenSeparators: [',']  }
                },
    

    Table:

                { data: 'tc',
                    render: '[, ].label',
                    editField: 'main.fk_test_cases_list[]',
                
                },
    

    in the table the test cases selected for a particular row are in an object called tc which contains an array of label/value pairs. The label is rendered into an array and tied to the Editor field main.fk_test_cases_list[]. The render is what displays the value rather than the ID. The [] is important for multi select.

    The options object is main.fk_test_cases_list[] and contains an array of label/value pair objects with all the options available to select.

    Hope this helps you get started.

    Kevin

This discussion has been closed.