Support

Account

Home Forums ACF PRO Populate Dynamic Select Field

Solved

Populate Dynamic Select Field

  • Hi

    I am using:

    function dynamic_dropdown_files( $field_members ){
    $field_members = [data from database];
    return $field_members;
    }

    add_filter(‘acf/load_field/name=unique_field_name’, ‘dynamic_dropdown_files’);

    to populate a select field. This is working but the it doesn’t quite work as expected.

    Whilst the select box is populated – it populates with new data that it has retrieved from the database BUT it doesn’t remove the old data/files I am retrieving which may have changed. Is there anyway to flush/clear the select and then populate it?

    Thanks.

  • The selection is under the ‘choices’ key.

    
    function dynamic_dropdown_files( $field ){
        $something_dynamic = [
            'key_1' => 'value 1',
            'key_2' => 'value 2',
        ];
    
        $field['choices'] = $something_dynamic;
    
        return $field;
    }
    

    cheers

  • Hi Gummi

    Thanks for your response.

    That looks like you are just populating the key value pairs – I know how to do that. What is happening is that when I do what you have suggested it doesn’t seem clear the old values first. I wanted to know if there is a way to “flush”/”clear” the values first?

    Thanks again.

  • can you clarify a bit on what do you mean by “clear the old values”?
    do you mean, don’t populate the previously saved values?

    if that’s the case, you can overwrite the “value” key.

    
    add_filter('acf/prepare_field/name=unique_field_name', 'acf_clear_saved_value');
    function acf_clear_saved_value($field) {
        $field['choices'] = YOUR_DYNAMIC_CHOICES;
    
        // flush/clear the saved value
        $field['value'] = null;
    
        // or, set it to whatever the default
        $field['value'] = $field['default_value'];
    
        return $field;
    }
    

    p.s. In order to “flush/clear” the value, your select field setting needs to have “allow null” enabled.

    Cheers

  • Hi Gummi

    Thanks for your continued help.

    I was having an issue with old data from the third party remote database still hanging about in the database even though I had removed it from third party database. This seems to however have been because there was no null value. So it looks like your suggestion may be working! 🙂

    Thanks again.

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

The topic ‘Populate Dynamic Select Field’ is closed to new replies.