Select2 - saving ID and Text in two database fields

Select2 - saving ID and Text in two database fields

DeJaDeJa Posts: 1Questions: 1Answers: 0

Hello,

I’m currently in the process of including select2 in the editor and can’t continue at one point.

Basically loading and saving works through the ID and Ajax via fn.dataTable.Editor.

However, besides the ID, I also have to save the content / text in an separate field of the database.

Is there a solution?

Answers

  • allanallan Posts: 63,538Questions: 1Answers: 10,476 Site admin

    Yes - use dependent() on your Select2 field to set the label of the selected value as a hidden field. dependent() will run whenever the Select2 value changes, so they two will always be in sync.

    Allan

  • allanallan Posts: 63,538Questions: 1Answers: 10,476 Site admin

    p.s. Would a join not be a better option for this?

  • Detlef JaegerDetlef Jaeger Posts: 11Questions: 2Answers: 0
    edited April 2019

    Hello Allan,

    thanks for the quick reply and the helpful hint.
    I think I'm on the right path (or miles away ;-)).

    My current attempt:

    editor.dependent( 'MyFieldWhitSelect2', function ( val, data ) {
    if (val == null || val == ""){
    } else {
    var Text = editor.field('MyFieldWhitSelect2');
    editor.field('MyHiddenTextField').val( Text.? );
    }
    });

    How can I read the text of Select2 in the editor?

    PS: Inner Join is for a variety of reasons probably more a problem (free text input must also be possible).

  • allanallan Posts: 63,538Questions: 1Answers: 10,476 Site admin

    That looks about right. In the [Select2 documentation
    (https://select2.org/programmatic-control/retrieving-selections#using-a-jquery-selector) you would use something like:

    $('#mySelect2').find(':selected').text();
    

    Use field().input() to get the html element for the field.

    Allan

  • Detlef JaegerDetlef Jaeger Posts: 11Questions: 2Answers: 0

    Hello allan,

    many many thanks!
    I could finally implement with your help a very good solution.

    Another problem has now emerged.
    If an entry of select2 contains a very long text and this is selected, the edit-window is widened across the screen width and the user can’t save anymore.

  • Detlef JaegerDetlef Jaeger Posts: 11Questions: 2Answers: 0

    I still need help regarding the problem with the window width.
    What is the event that trigger the window width when selecting an item in select?

  • allanallan Posts: 63,538Questions: 1Answers: 10,476 Site admin

    Select2 has a width option which would seem to be ideal here. Set it to be element perhaps.

    Allan

  • Detlef JaegerDetlef Jaeger Posts: 11Questions: 2Answers: 0

    Thanks for the feedback. I could solve it by another, very special way (no return of the selected text).

This discussion has been closed.