Setting Select2 templateSelection via JSON

Setting Select2 templateSelection via JSON

blabablabablabablaba Posts: 47Questions: 19Answers: 0
edited August 2019 in Select

Hi, within pluginSelect2.js I have implemented a nice format:

function gender_ID (gender) {
  if (!gender.id) {
    return gender.text;
  }
  var $gender = $('<span><img src="/statics/img/gender/'+gender.id+'.svg" class="icon"> ' + gender.text + '</span>');
  return $gender;
};

The above format can be implemented by an Editor Select2 control in the fields array:

fields [
{
                name: "gender_ID",
                type: "select2",
                options: gender,
                attr: {
                    required: true
                },
                opts: {
                    placeholder: 'Gender identity',
                    templateSelection: gender_ID,
                    minimumResultsForSearch: -1
                }
            }
]

This works very well. However;

I want to use JSON sent from the server to create the fields array. I can recreate the above perfectly EXCEPT I am unable to figure out how to recreate gender_ID (a variable that has a function inside it).

I've tried placing the format functions into an object within pluginSelect2.js

var formats = {
    gender_ID: function(gender) {
        if (!gender.id) {
            return gender.text;
        }
        var $gender = $('<span><img src="/statics/img/gender/'+gender.id+'.svg" class="icon"> ' + gender.text + '</span>');
        return $gender;
    }
}

but I find I can't access it.

Any assistance gratefully received - I'm sure it must be simple, I'm at a loss though

This question has an accepted answers - jump to answer

Answers

  • blabablabablabablaba Posts: 47Questions: 19Answers: 0

    Update: What do you think of the following?

    A workable solution seems to be to use window['fnName'] to access the formatting function:

    var fields = new Array()
    
    $.each(data, function(i,v){
    
        var field = {attr:{}}
    
        switch(v.type){
            case 'text':
                            // Some code for text
                })
            break
            case 'select2':
                field.opts = {
                    ...v.placeholder && {placeholder: v.placeholder},
                    templateSelection: window[v.name],
                    minimumResultsForSearch: -1
                }
            break
            case 'datetime':
            break
        }
    
        fields.push(field)
    
        console.log(v.type)
    });
    
    
    

    Is the best way to refer to the function, to use window[fnName] ?

  • allanallan Posts: 61,972Questions: 1Answers: 10,160 Site admin
    Answer ✓

    I want to use JSON sent from the server to create the fields array.

    This is the key part. JSON can't contain a function, so yes, you'd need a workaround such as that which you suggest.

    Allan

This discussion has been closed.