Support

Account

Home Forums General Issues Select Field + Add your own option?

Solving

Select Field + Add your own option?

  • The only other idea I have is use acf/save_post to check a new text field value in the post, and if it exists, assign that to the Select drop down, but also save it in the database to the ACF field Select setting values. I might look into that.

    Perhaps this post helps https://support.advancedcustomfields.com/forums/topic/updating-field-settings-in-php/

  • I have done it. So if you want to create Select values on the fly you can use this code. This code saves the “value : Label” though which is what I need. It sanitises the value you enter to slugify it, so its saved as “my-customer : My Customer” in ACFs field choices. If the value is to be the label its easily adapted.

    You need to create a new text field for the “New” value you want to add. Then grab the old and new acf field_ids to use in the code.

    function amity_pre_save_post( $post_id )
    {
    	// Assign the field IDs to variables
    	$select_field_id = 'field_6346f63fec6c2';
    	$select_new_field_id = 'field_634ac0abf3d60';
    	
    	// IF the new field value post cintains a value, then proceed
    	if(isset($_POST['acf'][$select_new_field_id]) && $_POST['acf'][$select_new_field_id] != '')
    	{
    		// Assign the new value to label and value
    		$label = $_POST['acf'][$select_new_field_id];
    		$value = sanitize_title($label);
    		
    		// Get the ACF field settings
    		$field = get_field_object($select_field_id);
    
    		// Add the new fields value and label to the field settings
    		$field['choices'][$value] = $label;
    		
    		// Update ACF field settings - adds new value into Select fields Choices in DB
    		acf_update_field($field);
    		
    		// Asssign the Select field value to the new field value
    		$_POST['acf'][$select_field_id] = $value;
    		
    		// Clear the new field value as we want it blank every time
    		$_POST['acf'][$select_new_field_id] = '';
    	}
    }
    add_filter('acf/save_post' , 'amity_pre_save_post', 1, 1 );
Viewing 2 posts - 26 through 27 (of 27 total)

The topic ‘Select Field + Add your own option?’ is closed to new replies.