Support

Account

Home Forums Add-ons Flexible Content Field Populate select fields dynamically using JavaScript API

Solved

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.

    1. You can populate all of the field choices based on the value of the other field.
    2. At a minimum set at least one choice value based on the current value of the field and then repopulate all the values when by using adding a filter to the ready action in your java script.

    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');
Viewing 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.