Populating a select in an admin template



  • I am able to set its value via settings.sync & data-key. Is there a way to directly map the data-options to a setting value?

    If that's not possible, is the best way to retrieve the setting in the same method I do a settings.sync and set the options via JS?


  • Community Rep

    You can do that by registering a new settings plugin. Just add the registerPlugin call before you do your settings.sync()

    In the plugin, map the name/value pairs to an array using jQuery, then add the current value to the array.

    settings.registerPlugin({
    	types: ['mySelect'], // This is your data-type for the <select>
    	set: function (element, value, trim) {
    
    		// Here we set the options based on the name/value pairs that were saved previously.
    		element = $(element);
    		if (value) value.forEach(function (mapping) {
    			if (mapping.name === 'value') {
    				element.val(mapping.value);
    			}else{
    				element.append('<option value="'+mapping.value+'">'+mapping.name+'</option>');
    			}
    		});
    
    		//////////////////
    		// Here you probably want to append any default options if they don't already exist.
    		//////////////////
    	},
    	get: function (element, trim, empty) {
    
    		// Here we get the mapping for saving into the database.
    		element = $(element);
    		var	value = [];
    		element.children().each(function (i, option) {
    			option = $(option);
    			value.push({name:option.text(),value:option.attr('value')}); // Get the text and value of each <option>
    		});
    		value.push({name:'value',value:element.val()}); // Get the current value.
    		// return the mapping.
    		return value;
    	}
    });
    

    In the template, you would just do this:

    <select data-type="mySelect" data-key="something"></select>
    

Log in to reply
 


Looks like your connection to NodeBB was lost, please wait while we try to reconnect.