Support

Account

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);
                });