Home Forums Backend Issues (wp-admin) Populate a select field according to the value selection in another field


Populate a select field according to the value selection in another field

  • I’m using JSON to pre-fill a select field with units. But I have a lot of units, so I want to reduce the amount by loading them in disciplines selected in an earlier field. For example, if one selects “Humanities” in field A, I want to get all Humanities units and populate them in field B. I can use the prepare_field filter, and by selecting a discipline, and then saving the post, when I return to it I can get the correct units. But this is obviously clumsy. Can it be done in real time with another filter?

    I’ve tried other filters (acf/prepare_field, acf/load_field, acf/format_value) as I’m not confident on their differences, but haven’t had any success yet. Thank you for giving me any steer in the right direction.

     * Filter units by discipline
    function unitSelection( $unitSelect ) {
        if( !isset($_POST['acf']['field_A']) ):
    		$discipline = get_field( 'discipline') ;
            $discipline = 'all';
        // Declare empty array
        $unitSelect['choices'] = array();
        // Query with JSON
        $json = file_get_contents('' . $discipline . '/all.json');
        // Convert JSON to an array of posts
        $units = json_decode($json);
            foreach ($units as $unit) {
                $code = $unit -> unit -> code;
                $title = $unit -> unit -> title;
                // Add unit to choices
                $unitSelect['choices'][$code] = $title . ' (' . $code . ')';
        // Return the field
        return $unitSelect;
    add_filter('acf/prepare_field/key=field_B', 'unitSelection');
  • This needs to be done by adding JS and AJAX requests, a simple example can be found here

  • Thanks John. This looks like it could be an ambitious project for my level. But very keen to give it a crack and learn some new things. Thanks for setting me on the right path! I really appreciate it.

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

You must be logged in to reply to this topic.