Gravity Forms Create Optgroups to Separate Select Options

Feb 14, 2018

Gravity Forms Create Optgroups to Separate Select Options


This post was originally created on our sister site WP Cover.
View Original Article
February 14, 2018

Gravity Forms is another plugin that I leverage on the majority of sites I develop.  It’s well developed, well maintained, and has all the necessary features you would expect from a form builder.  While I was building a Gravity Form the other day, I had the need to create Optgroups within the default Drop Down field.  After doing a bit of searching, I stumbled across this great filter on Github.

/**
 * Filter Gravity Forms select field display to wrap optgroups where defined
 * USE:
 * set the value of the select option to `optgroup` within the form editor. The 
 * filter will then automagically wrap the options following until the start of 
 * the next option group
 */

add_filter( 'gform_field_content', 'filter_gf_select_optgroup', 10, 2 );
function filter_gf_select_optgroup( $input, $field ) {
    if ( $field->type == 'select' ) {
        $opt_placeholder_regex = strpos($input,'gf_placeholder') === false ? '' : "[^<>]+]*>";
        $opt_regex = "/]*>" . $opt_placeholder_regex . "(.*?)]*>/i";
        $opt_group_regex = "/]*>([^<>]+)]*>/i";

        preg_match($opt_regex, $input, $opt_values);
        $split_options = preg_split($opt_group_regex, $opt_values[1]);
        $optgroup_found = count($split_options) > 1;

        // sometimes first item in the split is blank
        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 .= "" . $option . '';
                }
            }
            $input = str_replace($opt_values[1], $fixed_options, $input);
        }
    }

    return $input;
}

 

How do you use it? First, copy and paste the above code into your active themes function.php file.

From there, you will want to create a Drop Down field within your Gravity Form and make sure the checkbox that states ‘Show Values’ is ticked. Next, add the value ‘optgroup’ wherever you want to create a new options group.

The result is a beautiful and more importantly, organized select drop down:

 

The post Gravity Forms Create Optgroups to Separate Select Options appeared first on WP Cover.

Additional News

Perfect!

Let's get started. Fill out the form below to email us or request a call back.