Random selecton from a dropdown list [RESOLVED]

Hi Shyju. I took a stab at this. See what you think. This is the form I used:

[SITE REMOVED]

Download that to your computer, save it as a json file on your desktop. Then in your WordPress dashboard, go to Forms > Import/Export > Import forms to load that form. Go to Edit the form, and note the Form ID. You’ll need that.

Next, add this code to your theme functions.php file or a custom functionality plugin if you are using one: [SITE REMOVED]

The code is below as well, but you can download it if that is easier to copy.

// change 638 to your form ID
add_filter( 'gform_pre_render_638', 'set_random_default' );
function set_random_default( $form ) {
	foreach( $form['fields'] as &$field ) {
		if( 2 === $field->id ) {
			GFCommon::log_debug( __METHOD__ . '(): Matched field ID.' );
			// count the number of choices, and subtract one, because this is a zero-based array
			$count = count ( $field->choices ) -1;
			GFCommon::log_debug( __METHOD__ . "(): Number of items in the array is {$count}." );
			// select a random integer from 0 to $count
			$choice_number = rand ( 0, $count );
			GFCommon::log_debug( __METHOD__ . "(): Selected {$choice_number} out of {$count} choices." );
			// make that choice 'selected'
			$field->choices[$choice_number]['isSelected'] = 1;
		}
	}
	return $form;
}

Change the form ID from 638 to the ID the form has on your site. You can see in the code that this will apply only to field 2 in form 638. You don’t need to change the field ID to use this code on the form I sent. You only need to change the form ID.

Let me know how that works for you. I ran it several times and it seemed to be working well for me. If you have any questions, please let me know.

1 Like