Home › Forums › Backend Issues (wp-admin) › ACF Javascript API – Dynamically Update select2 Field Options › Reply To: ACF Javascript API – Dynamically Update select2 Field Options
If anyone is interested in a simple fix to this other than @christian-denatorange-fr ‘s, I found a useful hook in the ACF JS API:
https://www.advancedcustomfields.com/resources/javascript-api/#actions-select2_init
Here, the configuration args that were passed to select2() in the initialization process are passed to the hook. This allows you to store them in order to re-use them when you need to re-initialize the field.
Here’s how I modify the html of dropdown items for example:
acf.addAction('select2_init', function( $select, args, settings, field ){
console.log("Select2 initialized with args: ", args);
args['templateResult'] = function (state) {
if (!state.id) {
return state.text;
} else {
//Note that this html will not be escaped further on. If you need to escape, do it here!
let $state = "<div class='item'>" + state.text + "<span class='label'>Add</span></div>";
return jQuery($state);
}
};
//Reinit
$select.select2(args);
});
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.