If you work with Gravity Forms and build your WordPress themes on Bootstrap, you may find the following function quite useful.

Gravity Forms Filter

Read more about the gform_field_content filter.

add_filter("gform_field_content", "bootstrap_styles_for_gravityforms_fields", 10, 5);

Custom Function to Add Bootstrap Classes

The following function uses str_replace() which was chosen for this task because it effectively modifies only the small bit of the string we need it to. Gravity Forms has a reliable structure, so we just insert class names as needed for our common form field types.

If you need to expand this function, I suggest viewing the source of your published form so that you copy the GF output accurately and save yourself some head scratching (for example, attributes enclose values with single instead of double-quotes).

function bootstrap_styles_for_gravityforms_fields($content, $field, $value, $lead_id, $form_id){
	
    // Currently only applies to most common field types, but could be expanded.
	
    if($field["type"] != 'hidden' && $field["type"] != 'list' && $field["type"] != 'multiselect' && $field["type"] != 'checkbox' && $field["type"] != 'fileupload' && $field["type"] != 'date' && $field["type"] != 'html' && $field["type"] != 'address') {
        $content = str_replace('class=\'medium', 'class=\'form-control medium', $content);
    }
	
    if($field["type"] == 'name' || $field["type"] == 'address') {
        $content = str_replace('<input ', '<input class=\'form-control\' ', $content);
    }
	
    if($field["type"] == 'textarea') {
        $content = str_replace('class=\'textarea', 'class=\'form-control textarea', $content);
    }
	
    if($field["type"] == 'checkbox') {
        $content = str_replace('li class=\'', 'li class=\'checkbox ', $content);
        $content = str_replace('<input ', '<input style=\'margin-left:1px;\' ', $content);
    }
	
    if($field["type"] == 'radio') {
        $content = str_replace('li class=\'', 'li class=\'radio ', $content);
        $content = str_replace('<input ', '<input style=\'margin-left:1px;\' ', $content);
    }
	
	return $content;
	
} // End bootstrap_styles_for_gravityforms_fields()

Contribute to this project on Github

Related Topics

Bootstrap | Forms | Snippets

  • Robert Baker

    Hi. Thank you so much for this…this was very useful. Question, though. What about the select dropdowns and datepicker ones? Those don’t seem to style.