PLEASE NOTE: These forums are no longer utilized and are provided as an archive for informational purposes only. All support issues will be handled via email using our support ticket system. For more detailed information on this change, please see this blog post.

Dynamically Modify Checkbox/Radio Choices

  1. Have a client who wants to use our plugin (an event calendar plugin) to dynamically list upcoming events in their Gravity Forms plugin for event registration. I took a look at GF and found this filter somewhat useful: gform_field_choices_# (where # is the form ID).

    This is the sample code I came up with for him (without the specifics for my form):

    function testing_gform_field_choices( $choices, $field ) {
    
    		if ( 1 == $field['id'] ) { // 1 = the Field ID of the field you're wanting to modify.
    
    			unset( $field['choices'] );
    
    			$field['choices'][] = array(
    				'text' 			=> 'Testing 1',
    				'value'			=> 'Testing 1',
    				'isSelected'	=> false,
    				'price'			=> false
    			);
    
    			$field['choices'][] = array(
    				'text' 			=> 'Testing 2',
    				'value'			=> 'Testing 2',
    				'isSelected'	=> false,
    				'price'			=> false
    			);
    			$field['formId'] = 'DO_NOT_RUN'; // We don't want to get into an endless add_filter loop, so change the ID to someting useless.
    			$choices = GFCommon::get_radio_choices( $field, '', '' ); // Rerun the GF script to make it look pretty again
    
    		}
    
    		return $choices;
    
    	}
    	add_filter( 'gform_field_choices_1', 'testing_gform_field_choices', 10, 2 ); // _1 = the FORM ID of the form you want to modify

    So, I unset choices, add my "dynamic" choices, change the 'formID' to some junk value (so the filter doesn't run in an endless loop), get my new $choices variable and return it.

    It would be great if there was a "pre_gfrom_field_choices" filter at the head of the get_radio_choices and get_checkbox_choices functions. One that simply let us modify the $field['choices'] array. Doing it this way doubles the work... not a huge deal, but would be a good addition tot he code.

    Anyway, if that doesn't come to fruition, I hope the above code helps someone who wants to do something similar.

    Lew Ayotte

    Posted 12 years ago on Wednesday March 21, 2012 | Permalink