Select2 4.x and ajax

Select2 4.x and ajax

zajczajc Posts: 67Questions: 10Answers: 2
edited January 2016 in Editor

I have two fields, field_group_id and field_id which is select2 type. I would like to update field_id with json values from database based on field_group_id.

    , {
        "label": "field_group_id",
        "name": "field_group_id",
        "type": "select2"
      }, {
        "label": "field_id",
        "name": "field_id",
        "type": "select2"
      }

When I open edit form it trigger this:

editor.on('initEdit', function(e, node, data) {
  $.ajax({
    url: 'php/json.php',
    data: {
      grpID: data.field_group_id
    },
    dataType: 'json',
    success: function(json) {
      editor.field('field_id').update(json);
     //I need to add this
      editor.field('field_id').set(data.field_id);
    }
  });
});

This update field_id and set the field_id value and it is also marked selected in select2 dropdown list but the value is not showed on the screen. If I set "async: false" it works.

If I set type field to "select" it works if async:true is chosen and I also don't need this part "editor.field('field_id').set(data.field_id);"

I guess it is select2 plugin problem because the "select" doesn't have any problem. Any idea?

Replies

  • zajczajc Posts: 67Questions: 10Answers: 2

    Well I found out the workaround. In the official plugin for Select2 4.0.1

    set: function ( conf, val ) {
        conf._input.select2( 'val', val );
    },
    

    I put what Allan suggested in forum

    set: function(conf, val) {
        conf._input.val(val);
    }
    

    I extended this with trigger('change')

    set: function(conf, val) {
        conf._input.val(val).trigger('change');
    },
    

    So now I can update the Select2 field with ajax with async:true but still need to set the value with field().set().

    editor.on('initEdit', function(e, node, data) {
      $.ajax({
        url: 'php/json.php',
        data: {
          grpID: data.field_group_id
        },
        dataType: 'json',
        success: function(json) {
          editor.field('field_id').update(json);
          //*plugin bug* the value is not passed by default for ajax so we set it again
          editor.field('field_id').set(data.field_id);
        }
      });
    });
    
  • allanallan Posts: 63,353Questions: 1Answers: 10,444 Site admin

    So now I can update the Select2 field with ajax with async:true but still need to set the value with field().set().

    I think that sounds correct. The set that is performed by the standard init Editor runs on edit, will try to set the value before the update happens (and therefore will likely fail).

    Good to hear you have it working now.

    Allan

This discussion has been closed.