Setting Select2 templateSelection via JSON
Setting Select2 templateSelection via JSON
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
Update: What do you think of the following?
A workable solution seems to be to use window['fnName'] to access the formatting function:
Is the best way to refer to the function, to use window[fnName] ?
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