Add optgroup support in Gravity Form

The optgroup tag is used to group related options in a select element (drop-down list). If you have a long list of options, groups of related options are easier to handle for a user.

How can I group values in a drop-down field in GF?

Add this code to your plugin or function file:

<?php
/*
* Add <optgroup> support for select fields
* Use the label you want, and enter 'optgroup' as the value to create a new optgroup
*/
add_filter( 'gform_field_content', 'wpster_optgroup_for_select_fields', 10, 2 );
function wpster_optgroup_for_select_fields( $input, $field ) {
	if ( $field->type == 'select' ) {
		$opt_placeholder_regex = strpos($input,'gf_placeholder') === false ? '' : "<\s*?option.*?class='gf_placeholder'>[^<>]+<\/option\b[^>]*>";
		$opt_regex = "/<\s*?select\b[^>]*>" . $opt_placeholder_regex . "(.*?)<\/select\b[^>]*>/i";
		$opt_group_regex = "/<\s*?option\s*?value='optgroup\b[^>]*>([^<>]+)<\/option\b[^>]*>/i";
		preg_match($opt_regex, $input, $opt_values);
		$split_options = preg_split($opt_group_regex, $opt_values[1]);
		$optgroup_found = count($split_options) > 1;
		if( strlen($split_options[0]) < 1 ){
			unset($split_options[0]);
			$split_options = array_values( $split_options );
		}
		if( $optgroup_found ){
			$fixed_options = '';
			preg_match_all($opt_group_regex, $opt_values[1], $opt_group_match);
			if( count($opt_group_match) > 1 ){
				foreach( $split_options as $index => $option ){
					$fixed_options .= "<optgroup label='" . $opt_group_match[1][$index] . "'>" . $option . '</optgroup>';
					}
				}
			$input = str_replace($opt_values[1], $fixed_options, $input);
		}
	}
	return $input;
}
?>

Submit a Comment

Your email address will not be published.