Random selecton from a dropdown list [RESOLVED]

How to get a random selection from the dropdown list items when the form loads…

Do you mean that you want a random option selected as the default value, when the form loads?

And if so, can you explain the use-case? I’ve not seen that question or functionality before. Please share are much information as you can about the request. Thank you.

Hi Chris… https://ask4nations.org/ at the bottom of the home page… we have a choice to adopt a country… so the visitor is able to choose a country. If they are not sure which country they need, the gravity form could able to choose a random country for them… Does that make sense ?

Hi Shyju. I took a stab at this. See what you think. This is the form I used:
https://gravityforms.chrishajer.com/wp-content/uploads/gravity_forms/files/638.json

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: https://gravityforms.chrishajer.com/wp-content/uploads/gravity_forms/files/638.php.txt

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.

Thanks Chris… You are awesome… It worked flawlessly.

1 Like

Great news! Thank you for the update.

© 2008 - 2019. Gravity Forms is a project by Rocketgenius Inc.