Support

Account

Home Forums Backend Issues (wp-admin) ACF Javascript API – Dynamically Update select2 Field Options

Solving

ACF Javascript API – Dynamically Update select2 Field Options

  • How can I use the ACF Javascript API to dynamically update a select2 field’s options after the edit page has already loaded? I have effectively updated the options on the select2_args filter, (ie, making certain options disabled). But when I try to do the same thing on the ‘load’ or a ‘show_field’ action by looping through a getFields array, I don’t see the live effect on the select options.

  • I don’t think you can do that directly with the ACF API. You need to target the .select2() object of the field…. and I don’t know how to do that.

    I found this which indicates that this is not technically possible in Select2 itself but there appears to be several work-a-rounds https://github.com/select2/select2/issues/2830

  • Yeah, that seems pretty messy. I don’t know that it’s a requirement, however, that this is a select2 select field. I just started from that angle. Assuming I just have a normal select field (ie, didn’t toggle ‘Stylized UI’ on the field), could I use the ACF JS API to dynamically change/add/delete options?

  • Actually, no, there’s nothing in the API that I’m aware of that will let you update the options in the select field. You’d still need to do it manually. The only way I’ve found to do this is to destroy all of the existing options and rebuild them every time. You can see an example of this here https://github.com/Hube2/acf-dynamic-ajax-select-example/blob/master/dynamic-select-example/dynamic-select-on-select.js in the “update_cities_on_state_change” function

  • I can give this a go. Thanks for the link. For as much as the ACF API can handle, I’m kind of surprised it doesn’t have built in field option editing. Seems like an instinctual use, especially since the conditional logic parts are philosophically the same.

  • Honestly, it does, but if it’s in there I can’t find it.

  • Did this in my tiny lib where I can dynamicaly populate ACF select list with the content of other ACF selected items.

    Feel free to check the code at https://github.com/chdenat/acf-xtend !

    The idea is to get the select associated to any select field and manage its content accordingly.

Viewing 7 posts - 1 through 7 (of 7 total)

You must be logged in to reply to this topic.

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 Cookie Policy. If you continue to use this site, you consent to our use of cookies.