Select2 in editor loads option instead of placeholder

Select2 in editor loads option instead of placeholder

ztevieztevie Posts: 101Questions: 23Answers: 5

Hi!
A small issue with a select2 field in an editor. Everything works as it should except when first pressing the create button, in the editor the select2 drop-down has the first option selected. If I close it down and open again, the placeholder is selected as I want.
Also, if I first open edit, closer it and then create, the placeholder is selected.
Something is happening in the first opening of create that doesn't happen if I load the editor after that. I guess it's not a editor issue, but something with select2​ making a search the first time. I have disabled search by using Infinity and don't allow multiple selections.
Any advice?

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,351Questions: 26Answers: 4,955

    I don't experience that problem with select2. The placeholder shows when I create a new record. Maybe you can post you Datatables init code and your JSON response with the data and options.

    Kevin

  • ztevieztevie Posts: 101Questions: 23Answers: 5
    edited May 2017

    I will when I'm at the computer...
    I have a select2 in another editor as well. But it's a standalone so in that case I'm doing an update with the values on Create.on.open. the placeholder is selected there as it should.
    Something is different regarding select2 the first time create editor is opened vs opened the 2nd time and forward...
    When doing edit the correct value is selected.

  • ztevieztevie Posts: 101Questions: 23Answers: 5
    edited May 2017

    Here's my code and response. Everything looks fine though, and everything works as it should except for this little quirk. I remember a problem with the other editor: The select2 was the first field in the editor there, and when it received focus on opening the editor the same thing would happen, The solution was to set focus to null or to another field. I guess some how when opening editor the first time the values are initialized and get focus while values are read in?
    But aren't the values read in the same way when opening it a second time?
    THe select2 field is shiftdelays.delaystatus_id:

    dEditor = new $.fn.dataTable.Editor( {
        ajax: {
            url: "../_includes/process_shiftdelays.php",
            type: "POST",
            data: { sid: shiftActive }
        },
        table: "#tbl-delays",
        formOptions: {
            main: {
                submit: 'changed',
                focus: null
            }
        },
        fields: [ {
                label: "Starttid:",
                name:  "shiftdelays.shiftdelay_start"
            }, {
                label: "Sluttid:",
                name:  "shiftdelays.shiftdelay_end"  
            }, {
                label: "Kategori:",
                name:  "shiftdelays.delaystatus_id",
                type: "select2",
                opts: {
                    
                    placeholder: "Välj Kategori",
                    theme: "classic",
                    minimumResultsForSearch: "Infinity"
                }
            }, {
                label: "Beskrivning:",
                name:  "shiftdelays.shiftdelay_text",
                type: "textarea",
                attr: {
                    maxLength: 50
                }
            }
        ]
    } );
    dTable = $('#tbl-delays').DataTable( {
        language: {
            "url": "js/helpers/Swedish.json"
        },
        dom: 'tB',
        responsive: true,
        processing: true,
        ajax: {
            url: "../_includes/process_shiftdelays.php",
            type: 'POST',
            data: {sid: shiftActive}
        },
        order: [ 1, 'asc' ],
        columns: [
            {
                "className":      'details-control dt-center',
                "orderable":      false,
                "data":           null,
                "defaultContent": '',
                responsivePriority: 2
            },
            { data: null,
                render: function(data, type, row){
                    return data.shiftdelays.shiftdelay_start + '-' + data.shiftdelays.shiftdelay_end;
                },
                responsivePriority: 1,
                className: "all"
            },
            { data: "shiftdelays.shiftdelay_text",
                className: "none"
            },
            { data: null,
                render: function(data, type, row){
                    return '<i class="' + data.delaystatus.delaystatus_icon + '" data-toggle="tooltip" title="' + data.delaystatus.delaystatus_name + '"
                },
                responsivePriority: 5,
                className: "dt-center all"
            },
            { data: null,
                defaultContent: '<a href="#" class="dEdit" data-toggle="tooltip" title="Redigera"><i class="fa fa-pencil-square-o"><i/></a>',
                orderable: false,
                responsivePriority: 3,
                className: "all"
            },
            { data: null,
                defaultContent: '<a href="#" class="dRemove" data-toggle="tooltip" title="Ta bort"><i class="fa fa-eraser" style="color:red;"><i/></a>',
                orderable: false,
                responsivePriority: 4,
                className: "all"
            }
        ],
        select: false,
        buttons: [
            { extend: 'create',
                editor: dEditor,
                text: '<i class="fa fa-tags"></i> NY STÖRNING',
                formTitle: '<i class="fa fa-tags"></i> Skapa ny störning',
                formButtons: [{
                    label: '<i class="fa fa-undo"></i> Avbryt',
                    fn: function() { this.close(); }
                    },
                    '<i class="fa fa-floppy-o"></i> Spara'
                ]
            }
        ]
    } );
    
    Editor::inst( $db, 'shiftdelays', 'shiftdelay_id' )
        ->debug(true)
        ->field(
            Field::inst( 'shiftdelays.shiftdelay_start' ),
            Field::inst( 'shiftdelays.shiftdelay_end' ),
            Field::inst( 'shiftdelays.shiftdelay_text' ),
            Field::inst( 'shiftdelays.delaystatus_id' )
                ->options( 'delaystatus', 'delaystatus_id', 'delaystatus_name', '', '', 'delaystatus_id' ),
            Field::inst( 'delaystatus.delaystatus_name' )
                ->set(false),
            Field::inst( 'delaystatus.delaystatus_icon' )
                ->set(false)
        )
        ->leftJoin( 'delaystatus', 'delaystatus.delaystatus_id', '=', 'shiftdelays.delaystatus_id' )
        /*->join(
            Mjoin::inst( 'drillrigs' )
                ->link( 'blasts.blast_id', 'blastrigconn.blast_id' )
                ->link( 'drillrigs.rig_id', 'blastrigconn.rig_id' )
                ->order( 'rig_name asc' )
                ->fields(
                    Field::inst( 'rig_id' )
                        ->options( 'drillrigs', 'rig_id', 'rig_name' ),
                    Field::inst( 'rig_name' )
                )
        )*/
        ->where('shiftdelays.shift_id', $_POST["sid"], '=')
        ->process($_POST)
        ->json();
    

    THe response, options are the last SELECT:

    {"data":[{"DT_RowId":"row_1","shiftdelays":{"shiftdelay_start":"10:35","shiftdelay_end":"12:30","shiftdelay_text":"Hela riggen skakade och exploderade! ywe22","delaystatus_id":"1"},"delaystatus":{"delaystatus_name":"Reparation","delaystatus_icon":"fa fa-wrench"}},{"DT_RowId":"row_2","shiftdelays":{"shiftdelay_start":"09:25","shiftdelay_end":"09:56","shiftdelay_text":"Ojojoj, vad herregud s\u00e5 YYhemskt... AJAJ","delaystatus_id":"4"},"delaystatus":{"delaystatus_name":"FU","delaystatus_icon":"fa fa-medkit"}}],"options":{"shiftdelays.delaystatus_id":[{"label":"Reparation","value":"1"},{"label":"Ingen borrplats","value":"2"},{"label":"Str\u00f6ml\u00f6s","value":"3"},{"label":"FU","value":"4"},{"label":"Annat","value":"5"}]},"files":[],"debugSql":[{"query":"SELECT shiftdelays.shiftdelay_id as 'shiftdelays.shiftdelay_id', shiftdelays.shiftdelay_start as 'shiftdelays.shiftdelay_start', shiftdelays.shiftdelay_end as 'shiftdelays.shiftdelay_end', shiftdelays.shiftdelay_text as 'shiftdelays.shiftdelay_text', shiftdelays.delaystatus_id as 'shiftdelays.delaystatus_id', delaystatus.delaystatus_name as 'delaystatus.delaystatus_name', delaystatus.delaystatus_icon as 'delaystatus.delaystatus_icon' FROM shiftdelays LEFT JOIN delaystatus ON delaystatus.delaystatus_id = shiftdelays.delaystatus_id WHERE shiftdelays.shift_id = :where_0 ","bindings":[{"name":":where_0","value":"8","type":null}]},{"query":"SELECT DISTINCT delaystatus_id as 'delaystatus_id', delaystatus_name as 'delaystatus_name' FROM delaystatus ORDER BY delaystatus_id ","bindings":[]}]}

  • kthorngrenkthorngren Posts: 21,351Questions: 26Answers: 4,955

    I don't immediately see any glaring differences between what you are doing and my environment, except that I display my select2 fields in the table. I removed one from the table and datatable config and it still displays the placeholder.

    I don't use minimumResultsForSearch: "Infinity" but found it doesn't make a difference in my environment.

    The only thing that comes to mind is version differences. I first tried with DT 1.10.13 then 1.10.15. I'm using select2 version 4.0.3. If you ware using something different I may be able to try it on my system.

    Kevin

  • ztevieztevie Posts: 101Questions: 23Answers: 5

    I downloaded the bundle here, and the Select2 version included seems to be 4.0.1, DT is 1.10.15...
    Worth mentioning is that if I make it a normal select the placeholder works as intended and is selected at first opening...
    IS there another way to disable search on select2 than minimumResultsForSearch: "Infinity"?
    It seems as a workaround instead of having a method like search: disabled?

  • kthorngrenkthorngren Posts: 21,351Questions: 26Answers: 4,955

    I downloaded the select2 plugin from the plugins page and tried again with your versions. Still works (I cleared the browser's cache). I'm using Chrome on a Mac. What browser are you using?

    Their docs state that minimumResultsForSearch: "Infinity" is the way to hide the search box:
    https://select2.github.io/examples.html#hide-search

    Most of my select2 columns are multi select enabled which also hides the search box but allows for selecting more than one items (obviously :smile: ) so probably not what you want. I hadn't seen that option before so I may use it on a couple of single select2 columns I have.

    I'm out of ideas. Hopefully Allan can provide some next steps.

    Kevin

  • ztevieztevie Posts: 101Questions: 23Answers: 5
    edited May 2017

    Firefox, pc..
    I did try to download 4.0.3 but no difference...
    Yeah, hope Alan can figure out what's different between opening editor the first time and after that. I still think it has something to do with select2 triggering a search the first time. The search gives no result so it returns the first value in the list...
    The infinity method hide the search but it's not disabled I guess.

  • kthorngrenkthorngren Posts: 21,351Questions: 26Answers: 4,955

    The attached image shows my single select2 column. It shows the placeholder, the search box and the options. I clicked the Create button first after loading the page.

    I tried with Firefox and it works also.

    Kevin

  • ztevieztevie Posts: 101Questions: 23Answers: 5

    Could you try something for me?
    Set focus to a select2 field like so:
    formOptions: {
    main: {
    submit: 'changed',
    focus: 2 //or something
    }
    },

    You should be able to reproduce what's happening, otherwise it's very weird...

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

    @ztevie - Are you able to give me a link to the page so I can attempt to debug it?

    Thanks,
    Allan

  • ztevieztevie Posts: 101Questions: 23Answers: 5

    I'm sorry, this project is not available from outside... It's a pain in situations like this.
    But... Maybe you can help by just clarify what is different when clicking New button the first time, closing it and then open again?

    This occur only the very first time I click New(create). Closing and opening again works fine. Even opening edit on a row, closing it and then open create will work fine. Once I opened it the first time I have to reload the page to reproduce the problem.

    I mentioned above I had a similar problem with a Select2 field. THat was in a standalone so I did a update on the field with values from my own php-script:

    bEditor.on('open', function(e, mode, action){
                this.field("bitmodels.bitbrand_id").update(bBrands);
            });
    

    In this case the select2 did the same thing, selecting first option instead of placeholder. Here I found that because the field was the first one it received focus and thus selected an option. Setting the focus to null or another field solved the problem there...
    Here it doesn't work. There must be a difference because I load data the "normal" way, and select2 somehow assumes clicking when data is loaded during the table init?

  • ztevieztevie Posts: 101Questions: 23Answers: 5

    I tried to do an update of the field on editor.open, as I did with the other standalone editor. But the problem persists, "opt1" is selected...

    dEditor.on('open', function(e){
                this.field("shiftdelays.delaystatus_id").update([{"label":"opt1", "value":"1"}, {"label":"opt2", "value":"2"}]);
            });
    

    One thing I noticed with select2 is that once you choose an option you can not rechoose the placeholder. It's simply gone from the list...

  • kthorngrenkthorngren Posts: 21,351Questions: 26Answers: 4,955
    Answer ✓

    Set focus to a select2 field like so:
    I set the focus to the select2 field (2) and null. Still works as expected.

    I found this:
    https://select2.github.io/options.html#my-first-option-is-being-displayed-instead-of-my-placeholder

    However in my case the first option in the select is not blank and it works for me with both Chrome and Firefox. I also have this which may negate the need for a blank option:
    <span class="select2-selection__placeholder">Select a Publisher</span>

    I'm curious if you try this if it helps:
    https://select2.github.io/options.html#can-i-use-an-option-without-a-blank-value-as-my-placeholder

    Kevin

  • ztevieztevie Posts: 101Questions: 23Answers: 5
    edited May 2017

    OK, You got me on the right track! Thanks a lot!
    Option without a blank valule did not work, but I did this:

    dEditor.on('open', function(e){
                $("#DTE_Field_shiftdelays-delaystatus_id").prepend("<option value='0' selected='selected'></option>");
            });
    

    And in dEditor I added this:

    {
                        label: "Kategori:",
                        name:  "shiftdelays.delaystatus_id",
                        opts: {
                            minimumResultsForSearch: "Infinity",
                            placeholder: { id: "0", text: "Välj Kategori" },
                            theme: "classic"
                        },
                        type: "select2"
                    },
    

    Now it works in Firefox! I should mention it did work in latest Chrome without this fix... Weird...
    Thanks anyway, issue solved!

  • ztevieztevie Posts: 101Questions: 23Answers: 5

    And a fix for the fix. The open method will also make edit() get the extra option + placeholder selected which is not that good.
    So a check if action is create is needed:

    dEditor.on('open', function(e, mode, action){
                if(action === 'create'){
                    $("#DTE_Field_shiftdelays-delaystatus_id").prepend("<option value='0' selected='selected'></option>");
                }
            });
    
  • farmerphfarmerph Posts: 10Questions: 2Answers: 0

    I tried this

        dEditor.on('open', function(e, mode, action){
            if(action === 'create'){
                $("#DTE_Field_shiftdelays-delaystatus_id").prepend("<option value='0' 
                 selected='selected'></option>");
                }
            });
    

    It worked once. After i close the editor and reopen it I am back to square one the first option in the select is selected. I have been googling and reading all day and have not found anything. I have even tried

    dEditor.on('open', function(e, mode, action){
            if(action === 'create'){
                $("#DTE_Field_shiftdelays-delaystatus_id").attr("data-placeholder", "Placeholdertext");
                }
            });
    

    and again it only works the first time I open the editor.

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

    @farmerph - Can you give me a link to the page showing the issue so I can help to debug it please?

    Allan

This discussion has been closed.