Home › Forums › Backend Issues (wp-admin) › 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') ;
else:
$discipline = 'all';
endif;
// Declare empty array
$unitSelect['choices'] = array();
// Query with JSON
$json = file_get_contents('https://college.edu/units/' . $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 https://github.com/Hube2/acf-dynamic-ajax-select-example/tree/master/dynamic-select-example
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.
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.