Home › Forums › Add-ons › Flexible Content Field › Populate select fields dynamically using JavaScript API
I have three fields: Post Types, Taxonomies and Terms. When a post type is selected, I’m using ACF JavaScript API + AJAX to load related taxonomies and so on:
acf.addAction('new_field/name=select_type', getTaxonomies);
This is working fine. My problem now is how to populate Taxonomies and Terms fields after publish (reload) a post. It’s look like that Taxonomies and Terms doesn’t store the selected options.
The issue is that the selected value is not available in the choices when the field is loaded and displayed. There needs to be two parts, the JS AJAX part that your using and a PHP part that creates the choices when the field is initially displayed.
This can be accomplished by creating an acf/prepare_field filter. In this filter you can do 1 of 2 things.
I generally opt for #1 because it is faster and easier to do this in php rather than make the extra AJAX request.
Thanks for the reply @hube2. Just a question: how can I get the selected value of the other field inside prepare_field
filter? How can I get the selected post type to return the related taxonomies?
All of the other acf function will work inside of the filter to get the values in the values for the other fields.
The only complication might be if you are working with repeater fields or flex fields.
Oh, and if you want to just set one value and do the rest in JS and AJAX
$field['choices'][$field['value']] = $field['value'];
will usually set the current value as a choice so that the current choice is shown.
Thanks for the help John!
As I’m working with flexible content, I had to get the index:
$index = preg_replace('/\D/', '', $field['id']);
$post_type = get_field('content_'.$index.'_select_post_type');
You must be logged in to reply to this topic.
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.