Home Forums Backend Issues (wp-admin) Dynamically adding to choices on save


Dynamically adding to choices on save

  • I have a single-row repeater that has a select field and an input field. The user should be able to use the text field to add a missing choice to the select. When the post gets saved, the select choices should update to include the new choice and the text field should be cleared.

    I was having some success with my own solution, but at some point it stopped working, with some very weird results (like the updated select having its post-type changed!).

    The final function I wrote, which was supposed to do make the actual changes, is shown below.

    I would be very grateful if anyone could suggest an alternative method, as this is now an urgent problem for a client.


    function updateAssociatedSelect(
    	$parentFieldObject, $newChoice, $selectSubField, $textSubField, $postId
    ) {
    	// Get the field's post ID because acf_update_field() requires it
    	$selectSubField['ID'] = acf_get_field_id($selectSubField['key']);
    	// Update the select sub-field with the new choice if required
    	if (!in_array($newChoice, $selectSubField['choices'])) {
    		$selectSubField['choices'][$newChoice] = $newChoice;
    	// Update the post's values for the sub-fields
    	while (have_rows($parentFieldObject['key'], $postId)) {
    		// Get the existing choices
    		$values = get_sub_field($selectSubField['key']);
    		if (is_array($values)) {
    			// Add the new choice if there are already others...
    			array_push($values, $newChoice);
    		} else {
    			// ...or set $values to the new choice
    			$values = $newChoice;
    		// Add the new values to the select
    		update_sub_field($selectSubField['key'], $values); 
    		// Clear the text's value
    		update_sub_field($textSubField['key'], '');
Viewing 1 post (of 1 total)

The topic ‘Dynamically adding to choices on save’ is closed to new replies.