First and foremost, RocketGenius has, in my opinion, the best form creation plugin in the WordPress market, GravityForms. It seriously is worth every penny and probably is the best money I've spent. I see so much potential with Gravity Forms that has yet to be tapped, and I am excited to see new things from GravityForms and the GravityForms community.
GravityForms has made major strides this past year in their documentation. With their recent and ever-expanding hooks and filters, the ability to expand Gravity Forms is becoming limitless. If it doesn't do something that you want, with its current set of filters and hooks, you can easily code it to make it possible.
So recently, I needed to create a Terms of Service custom Gravity Forms field. This TOS field would be a read-only input box with a scrollbar disabling the submit button (as an option, even), so when the user scrolled to the bottom, it would enable the submit button.
Here are the steps that I've taken:
- Add the Button
- Add the Field Title
- Add the Input Field
- Add the Editor Form JS
- Add a Placement Custom Setting
- Add a ToolTip
- Add my Custom External JS
- Optional: Add the Appropriate CSS Classes
Add the Button
You will first need to hook into the gform_add_field_buttons. There are three Field Groups where you can add your button:
- Standard Fields
- Advanced Fields
- Post Fields
Also each button will need three things:
- Class
- Value (or Name)
- Onclick Action
So let's look at the function:
[php]
// Add a custom field button to the advanced to the field editor
add_filter( 'gform_add_field_buttons', 'wps_add_tos_field' );
function wps_add_tos_field( $field_groups ) {
foreach( $field_groups as &$group ){
if( $group["name"] == "advanced_fields" ){ // to add to the Advanced Fields
//if( $group["name"] == "standard_fields" ){ // to add to the Standard Fields
//if( $group["name"] == "post_fields" ){ // to add to the Standard Fields
$group["fields"][] = array(
"class"=>"button",
"value" => __("Terms of Service", "gravityforms"),
"onclick" => "StartAddField('tos');"
);
break;
}
}
return $field_groups;
}
[/php]
In the $group['fields']
array, in value, I used the 'gravityforms' text domain. Right? Wrong? or Indifferent? This can easily be changed to your theme's or child theme's text domain, since Gravity Forms more than likely won't have that string translated.
The most important thing here for me, and the things I changed are the value "Terms of Service" in the value key and the arg in the js command StartAddField, 'tos'.
Add the Field Title
Now that we have our button, we can click on it and a field box with the word Untitled will appear.
However, if you hover over it, only the slug, or the ID, or the type that was given will appear. In my previous bit of code, I gave it the ID, tos.
However, I do not want the type or the slug to appear, so I want to give it a title. To do this, I will need to hook into the filter gform_field_type_title, which is new in Gravity Forms 1.6. The code is fairly straight forward. I check to see if I have the correct type and then I apply a title.
[php]
// Adds title to GF custom field
add_filter( 'gform_field_type_title' , 'wps_tos_title' );
function wps_tos_title( $type ) {
if ( $type == 'tos' )
return __( 'Terms of Service' , 'gravityforms' );
}
[/php]
Add the Input Field
This may be one of the most important pieces of adding new Gravity Forms custom fields. To edit the input field, you will need to hook into the gform_field_input (or possibly even the gform_field_content hook). gform_field_input allows you to modify the field's input tag to create custom field types. gform_field_content allows users to completely modify the way the field is rendered including both the input field and label.
This hook has 5 parameters:
- $input: The input tag string to be filtered. Will be passed to the hook an empty string value. Return an empty string to bypass the filtering, or change its value to specify a new input tag
- $field: This is the Field Object, which contains all the values for the various field settings. The most important key in this object is the $field['type'], which allows you to filter and ensure that you are editing the correct input field.
- $value: The pre-populated default/initial value of the field
- $lead_id: When executed from the entry detail screen, $lead_id will be populated with the Entry ID. Otherwise, it will be 0
- $form_id: The Current Form ID, which will allow you to edit on a form by form basis
[php]
// Adds the input area to the external side
add_action( "gform_field_input" , "wps_tos_field_input", 10, 5 );
function wps_tos_field_input ( $input, $field, $value, $lead_id, $form_id ){
if ( $field["type"] == "tos" ) {
$max_chars = "";
if(!IS_ADMIN && !empty($field["maxLength"]) && is_numeric($field["maxLength"]))
$max_chars = self::get_counter_script($form_id, $field_id, $field["maxLength"]);
$input_name = $form_id .'_' . $field["id"];
$tabindex = GFCommon::get_tabindex();
$css = isset( $field['cssClass'] ) ? $field['cssClass'] : '';
return sprintf("<div class='ginput_container'><textarea readonly name='input_%s' id='%s' class='textarea gform_tos %s' $tabindex rows='10' cols='50'>%s</textarea></div>{$max_chars}", $field["id"], 'tos-'.$field['id'] , $field["type"] . ' ' . esc_attr( $css ) . ' ' . $field['size'] , esc_html($value));
}
return $input;
}
[/php]
First I am checking to make sure I am editing the display of the correct field type. Once that's been determined, I work on the max characters and tab index. Then I added the readonly and the CSS Classes from any custom entered CSS Classes (via cssClass) as well as the Size selection. However, again, this is fairly straightforward. For your custom fields, this will look vastly different. Once complete, your input/checkbox, etc, will appear.
Add the Editor Form JS
Now, probably one of the most important hooks for any new custom field. Without this hook, you won't see anything.
So to see the various placement settings under Properties and Advanced you will need to hook into gform_editor_js. This hook will allow you to inject JS into the form editor page.
[php]
// Now we execute some javascript technicalitites for the field to load correctly
add_action( "gform_editor_js", "wps_gform_editor_js" );
function wps_gform_editor_js(){
?>
<script type='text/javascript'>
jQuery(document).ready(function($) {
//Add all textarea settings to the "TOS" field plus custom "tos_setting"
// fieldSettings["tos"] = fieldSettings["textarea"] + ", .tos_setting"; // this will show all fields that Paragraph Text field shows plus my custom setting
// from forms.js; can add custom "tos_setting" as well
fieldSettings["tos"] = ".label_setting, .description_setting, .admin_label_setting, .size_setting, .default_value_textarea_setting, .error_message_setting, .css_class_setting, .visibility_setting, .tos_setting"; //this will show all the fields of the Paragraph Text field minus a couple that I didn't want to appear.
//binding to the load field settings event to initialize the checkbox
$(document).bind("gform_load_field_settings", function(event, field, form){
jQuery("#field_tos").attr("checked", field["field_tos"] == true);
$("#field_tos_value").val(field["tos"]);
});
});
</script>
<?php
}
[/php]
I don't claim to be a jQuery/javascript person. Never have and probably never will. However, I do know from what this bit of code does, two things: (1) You must set your custom settings (i.e., fieldSettings["tos"]), or nothing appears. This can take all the fields of another setting or a comma-separated string of settings. Also note that these are class names. and (2) You want to hook into gform_load_field_settings for any custom placement fields. The documentation for gform_editor_js isn't that great but if you look at gform_field_advanced_settings or gform_field_standard_settings you will see other examples of this hook in action.
Add a Placement Custom Setting
Now, with custom settings, you will want, even need, to add custom placement input fields. To do this you will need to hook into one of two hooks (gform_field_advanced_settings or gform_field_standard_settings), depending on where you want the custom placement input field.
Since I wanted to add my custom placement field to the Advanced Settings, I am hooking into gform_field_advanced_settings. In this example, I am adding a checkbox placement.
[php]
// Add a custom setting to the tos advanced field
add_action( "gform_field_advanced_settings" , "wps_tos_settings" , 10, 2 );
function wps_tos_settings( $position, $form_id ){
// Create settings on position 50 (right after Field Label)
if( $position == 50 ){
?>
<li class="tos_setting field_setting">
<input type="checkbox" id="field_tos" onclick="SetFieldProperty('field_tos', this.checked);" />
<label for="field_tos" class="inline">
<?php _e("Disable Submit Button", "gravityforms"); ?>
<?php gform_tooltip("form_field_tos"); ?>
</label>
</li>
<?php
}
}
[/php]
While I did not use this, here is another example of
Now both gform_field_standard_settings and gform_field_advanced_settings have various positions to hook into, which will determine the placement of the custom setting. So you can use various positions to determine which position you should place yours. For your information, here is the order/position for the [expand title="Standard Settings"]
- label_setting
- product_field_setting
- shipping_field_type_setting
- base_price_setting
- disable_quantity_setting
- option_field_type_setting
- donation_field_type_setting
- quantity_field_type_setting
- content_setting
- next_button_setting
- previous_button_setting
- disable_margins_setting
- post_custom_field_type_setting
- post_tage_type_setting
- captcha_theme_setting
- post_custom_field_setting
- post_status_setting
- post_author_setting
- post_category_setting
- post_category_checkbox_setting
- post_category_initial_item_setting
- gfield_post_category_initial_item_containter
- post_content_template_setting
- post_tite_template_setting
- customfield_content_template_setting
- post_image_setting
- post_image_featured_image
- address_setting
- name_format_setting
- date_input_type_setting
- date_format_setting
- file_extensions_setting
- columns_setting
- max_rows_setting
- time_format_setting
- phone_format_setting
- choices_setting
- other_choice_setting
- email_confirm_setting
- password_strength_setting
- enable_enhanced_ui_setting
- gfield_min_strength_containter
- number_format_setting
- description_setting
- credit_card_setting
- credit_card_style_setting
- input_mask_setting
- maxlen_setting
- range_setting
- rules_setting
[/expand]
For your information, here is the order for the [expand title="Advanced Settings"]
- admin_label_setting
- size_setting
- default_value_setting
- default_value_textarea_setting
- error_message_setting
- credit_card_icon_style_setting
- captcha_language_setting
- css_class_setting
- add_icon_url_setting
- delete_icon_url_setting
- password_field_setting
- force_ssl_field_setting
- visibility_setting
- prepopulate_field_setting
- conditional_logic_field_setting
- conditional_logic_page_setting
- conditional_logic_nextbutton_setting
[/expand]
Add a ToolTip
Next is to add a tooltip, so you will need to hook into gform_tooltips.
ToolTips are fairly straight forward. Simply edit the tooltips. In to code below, I add a tooltip to my newly placed placement field and edit a tooltip of an existing placement field and tooltip.
[php]
//Filter to add a new tooltip
add_filter('gform_tooltips', 'wps_add_tos_tooltips');
function wps_add_tos_tooltips($tooltips){
$tooltips["form_field_tos"] = "<h6>Disable Submit Button</h6>Check the box if you would like to disable the submit button.";
$tooltips["form_field_default_value"] = "<h6>Default Value</h6>Enter the Terms of Service here.";
return $tooltips;
}
[/php]
Now, here are all the [expand title="ToolTips"]
- notification_send_to_email ToolTip -> Send To Email Address: Enter the email address you would like the administrator notification email sent to.
- notification_autoformat ToolTip -> Disable Auto-Formatting: When enabled, auto-formatting will insert paragraph breaks automatically. Disable auto-formatting when using HTML to create email notification content.
- notification_send_to_routing ToolTip -> Routing: Allows notification to be sent to different email addresses depending on values selected in the form.
- notification_from_email ToolTip -> From Email Address: Enter the email address you would like the administrator notification email sent from, or select the email from available email form fields.
- notification_from_name ToolTip -> From Name: Enter the name you would like the administrator notification email sent from, or select the name from available name fields.
- notification_reply_to ToolTip -> Reply To: Enter the email address you would like to be used as the reply to address for the administrator notification email.
- notification_bcc ToolTip -> Blind Carbon Copy Addresses: Enter a comma separated list of email addresses you would like to receive a BCC of the administrator notification email.
- autoresponder_send_to_email ToolTip -> Blind Carbon Copy Addresses: Select the email form field that the user notification email should be sent to.
- autoresponder_bcc ToolTip -> Blind Carbon Copy Addresses: Enter a comma separated list of email addresses you would like to receive a BCC of the user notification email.
- autoresponder_from ToolTip -> From Email Address: Enter the email address you would like the user notification email sent from.
- autoresponder_from_name ToolTip -> From Name: Enter the name you would like the user notification email sent from.
- autoresponder_reply_to ToolTip -> Reply To Address: Enter the email address you would like to be used as the reply to address for the user notification email.
- form_activity ToolTip -> Limit Form Activity: Limit the number of entries a form can generate and/or schedule a time period the form is active.
- form_limit_entries ToolTip -> Limit Number of Entries: Enter a number in the input box below to limit the number of entries allowed for this form. The form will become inactive when that number is reached.
- form_schedule_form ToolTip -> Schedule Form: Schedule a time period the form is active.
- form_honeypot ToolTip -> Enable Anti-spam honeypot: Enables the honeypot spam protection technique, which is an alternative to the reCAPTCHA field.
- form_animation ToolTip -> Enable Animation: Check this option to enable a sliding animation when displaying/hiding conditional logic fields.
- form_tile ToolTip -> Form Title: Enter the title of your form.
- form_description ToolTip -> Form Description: Enter a description for your form. This may be used for user instructions.
- form_label_placement ToolTip -> Form Label Placement: Select the label placement. Labels can be top aligned above a field, left aligned to the left of a field, or right aligned to the left of a field.
- form_description_placement ToolTip -> Description Placement: Select the description placement. Descriptions can be placed above the field inputs or below the field inputs.
- form_button_text ToolTip -> Form Button Text: Enter the text you would like to appear on the form submit button.
- form_button_image ToolTip -> Form Button Image: Enter the path to an image you would like to use as the form submit button.
- form_css_class ToolTip -> Form CSS Class Name: Enter the CSS class name you would like to use in order to override the default styles for this form.
- form_field_add_icon_url ToolTip -> Add Icon URL: Enter the URL of a custom image to replace the default 'add item' icon.
- form_field_delete_icon_url ToolTip -> Delete Icon URL: Enter the URL of a custom image to replace the default 'delete item' icon.
- form_confirmation_message ToolTip -> Confirmation Message Text: Enter the text you would like the user to see on the confirmation page of this form.
- form_confirmation_autoformat ToolTip -> Disable Auto-Formatting: When enabled, auto-formatting will insert paragraph breaks automatically. Disable auto-formatting when using HTML to create the confirmation content.
- form_redirect_to_webpage ToolTip -> Redirect Form to Page: Select the page you would like the user to be redirected to after they have submitted the form.
- form_redirect_to_url ToolTip -> Redirect Form to URL: Enter the URL of the webpage you would like the user to be redirected to after they have submitted the form.
- form_redirect_querystring ToolTip -> Pass Data Via Query String: To pass field data to the confirmation page, build a Query String using the 'Insert Merge Tag' drop down. ..more info on querystrings »
- form_field_label ToolTip -> Field Label: Enter the label of the form field. This is the field title the user will see when filling out the form.
- form_field_label_html ToolTip -> Field Label: Enter the label for this HTML block. It will help you identify your HTML blocks in the form editor, but it will not be displayed on the form.
- form_field_disable_margins ToolTip -> Disable Default Margins: When enabled, margins are added to properly align the HTML content with other form fields.
- form_field_recaptcha_theme ToolTip -> Recaptcha Theme: Select the visual theme for the reCAPTCHA field the available options to better match your site design.
- form_field_captcha_type ToolTip -> CAPTCHA Type: Select the type of CAPTCHA you would like to use.
- form_field_custom_field_name ToolTip -> Custom Field Name: Select the custom field name from available existing custom fields, or enter a new custom field name.
- form_field_type ToolTip -> Field type: Select the type of field from the available form fields.
- form_field_maxlength ToolTip -> Maximum Characters: Enter the maximum number of characters that this field is allowed to have.
- form_field_maxrows ToolTip -> Maximum Rows: Enter the maximum number of rows that users are allowed to add.
- form_field_date_input_type ToolTip -> Date Input Type: Select the type of inputs you would like to use for the date field. Date Picker will let users select a date from a calendar. Date Field will let users free type the date.
- form_field_address_type ToolTip -> Address Type: Select the type of address you would like to use.
- form_field_address_default_state_us ToolTip -> Default State: Select the state you would like to be selected by default when the form gets displayed.
- form_field_address_default_state_canadian ToolTip -> Default Province: Select the province you would like to be selected by default when the form gets displayed.
- form_field_address_default_country ToolTip -> Default Country: Select the country you would like to be selected by default when the form gets displayed.
- form_field_address_hide_country ToolTip -> Hide Country: For addresses that only apply to one country, you can choose to not display the country drop down. Entries will still be recorded with the selected country.
- form_field_address_hide_address2 ToolTip -> Hide Address Line 2: Check this box to prevent the extra address input (Address Line 2) from being displayed in the form.
- form_field_address_hide_state_us ToolTip -> Hide State Field: Check this box to prevent the State field from being displayed in the form.
- form_field_address_hide_state_canadian ToolTip -> Hide Province Field: Check this box to prevent Province field from being displayed in the form.
- form_field_address_hide_state_international ToolTip -> Hide State/Province/Region: Check this box to prevent the State/Province/Region from being displayed in the form.
- form_field_name_format ToolTip -> Field Name Format: Select the format you would like to use for the Name field. There are 3 options, Normal which includes First and Last Name, Extended which adds Prefix and Suffix, or Simple which is a single input field.
- form_field_number_format ToolTip -> Number Format: Select the format of numbers that are allowed in this field. You have the option to use a comma or a dot as the decimal separator.
- form_field_force_ssl ToolTip -> Force SSL: Check this box to prevent this field from being displayed in a non-secure page (i.e. not https://). It will redirect the page to the same URL, but starting with https:// instead. This option requires a properly configured SSL certificate.
- form_field_card_style ToolTip -> Credit Card Icon Style: Select the style you would like to use for the credit card icons.
- form_field_date_format Field Date Format: Select the format you would like to use for the date input. Available options are MM/DD/YYYY and DD/MM/YYYY.
- form_field_time_format ToolTip -> Time Format: Select the format you would like to use for the time field. Available options are 12 hour (i.e. 8:30 pm) and 24 hour (i.e. 20:30).
- form_field_fileupload_allowed_extensions ToolTip -> Allowed File Extensions: Enter that allowed file extensions for file uploads. This will limit what type of files a user may upload.
- form_field_phone_format ToolTip -> Phone Number Format: Select the format you would like to use for the phone input. Available options are domestic US/CANADA style phone number and international long format phone number.
- form_field_description ToolTip -> Field Description: Enter the description for the form field. This will be displayed to the user and provide some direction on how the field should be filled out or selected.
- form_field_required ToolTip -> Required Field: Select this option to make the form field required. A required field will prevent the form from being submitted if it is not filled out or selected.
- form_field_no_duplicate ToolTip -> No Duplicates: Select this option to limit user input to unique values only. This will require that a value entered in a field does not currently exist in the entry database for that field.
- form_field_number_range ToolTip -> Number Range: Enter the minimum and maximum values for this form field. This will require that the value entered by the user must fall within this range.
- form_field_admin_label ToolTip -> Admin Label: Enter the admin label of the form field. Entering a value in this field will override the Field Label when displayed in the Gravity Forms administration tool.
- form_field_size ToolTip -> Field Size: Select a form field size from the available options. This will set the width of the field.
- form_field_default_value ToolTip -> Default Value: If you would like to pre-populate the value of a field, enter it here.
- form_field_validation_message ToolTip -> Validation Message: If you would like to override the default error validation for a field, enter it here. This message will be displayed if there is an error with this field when the user submits the form.
- form_field_recaptcha_language ToolTip -> reCaptcha Language: Select the language you would like to use for the reCAPTCHA display from the available options.
- form_field_css_class ToolTip -> CSS Class Name: Enter the CSS class name you would like to use in order to override the default styles for this field.
- form_field_visibility ToolTip -> Visibility: Select the visibility for this field. Field visibility set to Everyone will be visible by the user submitting the form. Form field visibility set to Admin Only will only be visible within the Gravity Forms administration tool.Setting a field to Admin Only is useful for creating fields that can be used to set a status or priority level on submitted entries.
- form_field_choices ToolTip -> Field Choices: Add Choices to this field. You can mark each choice as checked by default by using the radio/checkbox fields on the left.
- form_field_choice_values ToolTip -> Enable Choice Values: Check this option to specify a value for each choice. Choice values are not displayed to the user viewing the form, but are accessible to administrators when viewing the entry.
- form_field_conditional_logic ToolTip -> Conditional Logic: Create rules to dynamically display or hide this field based on values from another field
- form_field_enable_enhanced_ui ToolTip -> Enable Enhanced UI: By selecting this option, the Chosen jQuery script will be applied to this field, enabling search capabilities to Drop Down fields and a more user-friendly interface for Multi Select fields.
- form_field_other_choice ToolTip -> Other Choice: Check this option to add a text input as the final choice of your radio button field. This allows the user to specify a value that is not a predefined choice.
- form_require_login ToolTip -> Require user to be logged in: Check this option to require a user to be logged in to view this form
- form_require_login_message ToolTip -> Require Login Message: Enter a message to be displayed to users who are not logged in (shortcodes and HTML are supported gravityforms
- form_page_conditional_logic ToolTip -> Page Conditional Logic: Create rules to dynamically display or hide this page based on values from another field
- form_progress_indicator ToolTip -> Progress Indicator: Select which type of visual progress indicator you would like to display. Progress Bar, Steps or None
- form_percentage_style ToolTip -> Progress Bar Style: Select which progress bar style you would like to use. Select custom to choose your own text and background color
- form_page_names ToolTip -> Page Names: Name each of the pages on your form. Page names are displayed with the selected progress indicator
- next_button_text ToolTip -> Next Button Text: Enter the text you would like to appear on the page next button
- next_button_image ToolTip -> Next Button Image: Enter the path to an image you would like to use as the page next button
- previous_button_text ToolTip -> Previous Button Text: Enter the text you would like to appear on the page previous button
- previous_button_image ToolTip -> Previous Button Image: Enter the path to an image you would like to use as the page previous button
- form_nextbutton_conditional_logic ToolTip -> Next Button Conditional Logic: Create rules to dynamically display or hide the page's Next Button based on values from another field
- form_button_conditional_logic ToolTip -> Conditional Logic: Create rules to dynamically display or hide the submit button based on values from another field
- form_field_post_category_selection ToolTip -> Post Category: Select which categories are displayed. You can choose to display all of them or select individual ones.
- form_field_post_status ToolTip -> Post Status: Select the post status that will be used for the post that is created by the form entry.
- form_field_post_author ToolTip -> Post Author: Select the author that will be used for the post that is created by the form entry.
- form_field_post_format ToolTip -> Post Format: Select the post format that will be used for the post that is created by the form entry.
- form_field_post_content_template_enable ToolTip -> Post Content Template: Check this option to format and insert merge tags into the Post Content.
- form_field_post_title_template_enable ToolTip -> Post Title Template: Check this option to format and insert merge tags into the Post Title.
- form_field_post_category ToolTip -> Post Category: Select the category that will be used for the post that is created by the form entry.
- form_field_current_user_as_author ToolTip -> Use Current User as Author: Selecting this option will set the post author to the WordPress user that submitted the form.
- form_field_image_meta ToolTip -> Image Meta: Select one or more image metadata field to be displayed along with the image upload field. They enable users to enter additional information about the uploaded image.
- form_field_featured_image ToolTip -> Set as Featured Image: Check this option to set this image as the post's Featured Image.
- form_field_prepopulate ToolTip -> Incoming Field Data: Check this option to enable data to be passed to the form and pre-populate this field dynamically. Data can be passed via Query Strings, Shortcode and/or Hooks
- form_field_content ToolTip -> Content: Enter the content (Text or HTML) to be displayed on the form.
- form_field_base_price ToolTip -> Base Price: Enter the base price for this product.
- form_field_disable_quantity ToolTip -> Disable Quantity: Disables the quantity field. A quantity of 1 will be assumed or you can add a Quantity field to your form from the Pricing Fields.
- form_field_product ToolTip -> Product Field: Select which Product this field is tied to.
- form_field_mask ToolTip -> Input Mask: Input masks provide a visual guide allowing users to more easily enter data in a specific format such as dates and phone numbers.
- form_standard_fields ToolTip -> Standard Fields: Standard Fields provide basic form functionality.
- form_advanced_fields ToolTip -> Advanced Fields: Advanced Fields are for specific uses. They enable advanced formatting of regularly used fields such as Name, Email, Address, etc.
- form_post_fields ToolTip -> Post Fields: Post Fields allow you to add fields to your form that create Post Drafts in WordPress from the submitted data.
- form_pricing_fields ToolTip -> Pricing Fields: Pricing fields allow you to add fields to your form that calculate pricing for selling goods and services.
- export_select_form ToolTip -> Export Selected Form: Select the form you would like to export entry data from. You may only export data from one form at a time.
- export_select_forms ToolTip -> Export Selected Forms: Select the forms you would like to export.
- export_select_fields ToolTip -> Export Selected Fields: Select the fields from the select form you would like to export data from.
- export_date_range ToolTip -> Export Date Range: Select a date range. Setting a range will only export entries submitted during that date range. If no range is set, all entries will be exported.
- settings_license_key ToolTip -> Settings License Key: Your Gravity Forms support license key is used to verify your support package, enable automatic updates and receive support.
- settings_output_css ToolTip -> Output CSS: Select yes or no to enable or disable CSS output. Setting this to no will disable the standard Gravity Forms CSS from being included in your theme.
- settings_html5 ToolTip -> Output HTML5: Select yes or no to enable or disable HTML5 output. Setting this to no will disable the standard Gravity Forms HTML5 form field output.
- settings_recaptcha_public ToolTip -> reCaptcha Public Key: Enter your reCAPTCHA Public Key, if you do not have a key you can register for one at the provided link. reCAPTCHA is a free service.
- settings_recaptcha_private ToolTip -> reCaptcha Private Key: Enter your reCAPTCHA Private Key, if you do not have a key you can register for one at the provided link. reCAPTCHA is a free service.
- settings_currency ToolTip -> Currency: Please select the currency for your location. Currency is used for pricing fields and price calculations.
- entries_conversion ToolTip -> Entries Conversion: Conversion is the percentage of form views that generated an entry. If a form was viewed twice, and one entry was generated, the conversion will be 50%.
- widget_tabindex ToolTip -> Tab Index Start Value: If you have other forms on the page (i.e. Comments Form specify a higher tabindex start value so that your Gravity Form does not end up with the same tabindices as your other forms. To disable the tabindex, enter 0 (zero).
- notification_override_email ToolTip -> Override Notifications: Enter a comma separated list of email addresses you would like to receive the selected notification emails.
[/expand]
Add my Custom External JS
Now my Advanced Custom Field would not be advanced or very custom if all I did was duplicate the Paragraph Text (textarea) field and add my custom placement field. Right now, the submit button does not disable for any reason.
So, I need to make some further modifications to achieve my goal. This included my own custom external JS. So I needed to hook into gform_enqueue_scripts, which would allow me to properly enqueue scripts Gravity Forms would like.
[php]
// Add a script to the display of the particular form only if tos field is being used
add_action( 'gform_enqueue_scripts' , 'wps_gform_enqueue_scripts' , 10 , 2 );
function wps_gform_enqueue_scripts( $form, $ajax ) {
// cycle through fields to see if tos is being used
foreach ( $form['fields'] as $field ) {
if ( ( $field['type'] == 'tos' ) && ( isset( $field['field_tos'] ) ) ) {
$url = plugins_url( 'gform_tos.js' , __FILE__ );
wp_enqueue_script( "gform_tos_script", $url , array("jquery"), '1.0' ); // Note WPS_JS is a constant I've set for all my child theme's custom JS.
break;
}
}
}
[/php]
Here is my JS, which is really simple (if I can understand it).
[javascript]
jQuery(document).ready(function($) {
$(".gform_footer input[type='submit']").prop("disabled",true);
$(".gform_body textarea.gform_tos").scroll(function(){
if($(this).scrollTop()+$(this).height() >= $(this)[0].scrollHeight-10){
$(".gform_footer input[type='submit']").prop("disabled",false);
}
});
});
[/javascript]
Add the Appropriate CSS Classes
Finally, in order to ease form display styling of the Terms of Service, I needed to make sure that I included a class. Now this could have been added with the gform_input_field hook, but I just wanted to display how it would work using this hook.
So I could hook into gform_field_css_class, which would allow me to add/change the CSS of the external fields. This hook is also great for all those designers who *cough*hate*cough* I mean love to style Gravity Forms CSS. Two little know documentation pages by Gravity Forms are its styling pages: CSS Ready Classes and CSS Targeting Samples. The interesting thing is that CSS Ready Classes gives an example of a Terms of Service, which requires a HTML box and a checkbox to state that you've read the TOS.
[php]
// Add a custom class to the field li
add_action("gform_field_css_class", "custom_class", 10, 3);
function custom_class($classes, $field, $form){
if( $field["type"] == "tos" ){
$classes .= " gform_tos";
}
return $classes;
}
[/php]
Here is a list of all the Gravity Forms [expand title="ready-to-use CSS classes."]
Halves
- : gf_left_half, gf_right_half
Thirds
- : gf_left_third, gf_middle_third, gf_right_third
Inline
- : gf_inline
List Classes
- : gf_list_2col, gf_list_3col, gf_list_4col, gf_list_5col, gf_list_inline
List Height Classes
- : gf_list_height_25, gf_list_height_50, gf_list_height_75, gf_list_height_100, gf_list_height_125, gf_list_height_150 (This applies a [X]px height value all multiple choice/checkbox items in that list. This can be useful to avoid "hanging floats" caused by list items of unequal height. This only applies to multiple choice/checkbox lists and work with any of the form label position settings.)
Other Classes
- : gf_scroll_text (hides the am/pm selector in the time field- this only hides the field on the form, not in the form entry tabl), gf_hide_charleft (hides the characters left counter beneath paragraph text fields when using the maximum characters option)
[/expand]
Note: the classes are added to the parent
- element surrounding a field so you can define your own class name and add your own rules to your theme stylesheet based on that class name being added to the field.
Download the Code
[download id="18"]
Here is the full code:
[php]
<?php
/**
* Plugin Name: Gravity Forms Terms of Service Field
* Terms of Service Gravity Forms Custom Form Field
* Plugin URI: https://wpsmith.net/2011/plugins/how-to-create-a-custom-form-field-in-gravity-forms-with-a-terms-of-service-form-field-example/
* Donate link: https://wpsmith.net/donation
* Description: The first generation of this plugin will set a default image for post thumbnails for the Genesis framework.
* Version: 0.2 beta
* Author: Travis Smith
* Author URI: http://www.wpsmith.net/
* License: GPLv2
*
* Copyright 2012 Travis Smith (email : http://www.wpsmith.net/contact)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
*
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
// Add a custom field button to the advanced to the field editor
add_filter( 'gform_add_field_buttons', 'wps_add_tos_field' );
function wps_add_tos_field( $field_groups ) {
foreach( $field_groups as &$group ){
if( $group["name"] == "advanced_fields" ){ // to add to the Advanced Fields
//if( $group["name"] == "standard_fields" ){ // to add to the Standard Fields
//if( $group["name"] == "post_fields" ){ // to add to the Standard Fields
$group["fields"][] = array(
"class"=>"button",
"value" => __("Terms of Service", "gravityforms"),
"onclick" => "StartAddField('tos');"
);
break;
}
}
return $field_groups;
}
// Adds title to GF custom field
add_filter( 'gform_field_type_title' , 'wps_tos_title' );
function wps_tos_title( $type ) {
if ( $type == 'tos' )
return __( 'Terms of Service' , 'gravityforms' );
}
// Adds the input area to the external side
add_action( "gform_field_input" , "wps_tos_field_input", 10, 5 );
function wps_tos_field_input ( $input, $field, $value, $lead_id, $form_id ){
if ( $field["type"] == "tos" ) {
$max_chars = "";
if(!IS_ADMIN && !empty($field["maxLength"]) && is_numeric($field["maxLength"]))
$max_chars = self::get_counter_script($form_id, $field_id, $field["maxLength"]);
$input_name = $form_id .'_' . $field["id"];
$tabindex = GFCommon::get_tabindex();
$css = isset( $field['cssClass'] ) ? $field['cssClass'] : '';
return sprintf("<div class='ginput_container'><textarea readonly name='input_%s' id='%s' class='textarea gform_tos %s' $tabindex rows='10' cols='50'>%s</textarea></div>{$max_chars}", $field["id"], 'tos-'.$field['id'] , $field["type"] . ' ' . esc_attr($css) . ' ' . $field['size'] , esc_html($value));
}
return $input;
}
// Now we execute some javascript technicalitites for the field to load correctly
add_action( "gform_editor_js", "wps_gform_editor_js" );
function wps_gform_editor_js(){
?>
<script type='text/javascript'>
jQuery(document).ready(function($) {
//Add all textarea settings to the "TOS" field plus custom "tos_setting"
// fieldSettings["tos"] = fieldSettings["textarea"] + ", .tos_setting"; // this will show all fields that Paragraph Text field shows plus my custom setting
// from forms.js; can add custom "tos_setting" as well
fieldSettings["tos"] = ".label_setting, .description_setting, .admin_label_setting, .size_setting, .default_value_textarea_setting, .error_message_setting, .css_class_setting, .visibility_setting, .tos_setting"; //this will show all the fields of the Paragraph Text field minus a couple that I didn't want to appear.
//binding to the load field settings event to initialize the checkbox
$(document).bind("gform_load_field_settings", function(event, field, form){
jQuery("#field_tos").attr("checked", field["field_tos"] == true);
$("#field_tos_value").val(field["tos"]);
});
});
</script>
<?php
}
// Add a custom setting to the tos advanced field
add_action( "gform_field_advanced_settings" , "wps_tos_settings" , 10, 2 );
function wps_tos_settings( $position, $form_id ){
// Create settings on position 50 (right after Field Label)
if( $position == 50 ){
?>
<li class="tos_setting field_setting">
<input type="checkbox" id="field_tos" onclick="SetFieldProperty('field_tos', this.checked);" />
<label for="field_tos" class="inline">
<?php _e("Disable Submit Button", "gravityforms"); ?>
<?php gform_tooltip("form_field_tos"); ?>
</label>
</li>
<?php
}
}
//Filter to add a new tooltip
add_filter('gform_tooltips', 'wps_add_tos_tooltips');
function wps_add_tos_tooltips($tooltips){
$tooltips["form_field_tos"] = "<h6>Disable Submit Button</h6>Check the box if you would like to disable the submit button.";
$tooltips["form_field_default_value"] = "<h6>Default Value</h6>Enter the Terms of Service here.";
return $tooltips;
}
// Add a script to the display of the particular form only if tos field is being used
add_action( 'gform_enqueue_scripts' , 'wps_gform_enqueue_scripts' , 10 , 2 );
function wps_gform_enqueue_scripts( $form, $ajax ) {
// cycle through fields to see if tos is being used
foreach ( $form['fields'] as $field ) {
if ( ( $field['type'] == 'tos' ) && ( isset( $field['field_tos'] ) ) ) {
$url = plugins_url( 'gform_tos.js' , __FILE__ );
wp_enqueue_script( "gform_tos_script", $url , array("jquery"), '1.0' );
break;
}
}
}
// Add a custom class to the field li
add_action("gform_field_css_class", "custom_class", 10, 3);
function custom_class($classes, $field, $form){
if( $field["type"] == "tos" ){
$classes .= " gform_tos";
}
return $classes;
}
[/php]
Charlie says
You hear a lot about how awesome and flexible Gravity forms is, but rarely see highly quality tuts – so thanks for writing this one!
Ryan Dennler says
I must say, this tutorial is gold. There are a couple of examples of how to add buttons on Pastebin but they obviously only show code and don’t go into the details of what actually works. This is PERFECT to start fooling around with Gravity Forms on a much higher level. Thanks man!
jami says
Hey Guys this is fantastic! I’ve got part way through it but one thing that I struggle with is finding where to add the code, i.e. into which files, or create a new file and if new files, where to save them..
Can you advise or add a readme to the download..
I can’t thank you enough for this fabulous work 🙂
Jami
Travis Smith says
Hello Jami,
This can go in your functions.php file or in a new file (which is my preference for organization reasons).
Fred Duzink says
Nice tutorial Travis!
So best way is to include it in functions.php with “include(get_template_directory().’/gftos/gftos.php’);”
But what about gform_tos.js? its not clear for me where to put that file.
Fred Duzink says
nevermind fixed it with “wp_enqueue_script( “gform_tos_script”, WP_CONTENT_URL . ‘/themes/*theme-name*/gftos/gform_tos.js’ , array(“jquery”), ‘1.0’ );”
Brian Dooley says
Hey man, great tutorial! this is EXACTLY what I was looking for. One note: in your (final code) line 76 and 77 have some quote disagreements. I changed it to this:
$(document).bind("gform_load_field_settings", function(event, field, form){
jQuery("#field_tos").attr("checked", field["field_tos"] == true);
$("#field_tos_value").val(field["tos"]);
});
Brian Dooley says
just kidding, as the code didn’t output fully…
i changed the quotes around the urls and the nofollows to single quotes. =)
Brian Dooley says
hmm…
upon further research, I’m finding that the “disable submit” checkbox keeps unticking itself.
hmm… any words of wisdom?
Again, great tutorial! Thanks!
Travis Smith says
This does not yet work with the AJAX version as there is a jQuery “conflict.” Simply, the Gravity Form jQuery over-rides the custom jQuery and removes the disable attribute. So using the TOS must be done in a non-AJAX form.
Kevin says
I added the above full code to my theme’s functions.php and now have my TOS button, the “untitled” blank text box and my “properties” & “Advanced” tabs… and nothing else. I obvious missed adding some code somewhere to make this work… but what and where?
Travis Smith says
Hello Kevin,
What do you mean “nothing else”? I am not sure how best to help you… You obviously have to fill out the Terms of Service and everything to make it work??
Kevin says
ISorry for not being clear… I have exactly what you show in your image under the heading:
“Add the Editor Form JS”
That’s all, nothing happens when I click tabs, etc. So I missed some additional code somewhere as I only copied and pasted your “FULL CODE” into my functions.php. What else do I need to add elsewhere?
Sorry… I don’t usually do code but when I found this tutorial I realized it was exactly what I needed for my new tour registration pages.
Thanks,
Kevin
Muhammad Abdul Qadoos says
hey nice article…
i want to replace submit button with replace.. how to do this 🙁 i am unable to find the way
Travis Smith says
That’s in the Advanced Settings when you are creating the form.
Mark says
I added your code to a fresh wordpress install and I can’t get the Terms of Service button to appear. Is this code compatitable with the latest version of wordpress? 3.3.1
Travis Smith says
Hello Mark, Yes it works. When GF updated, I had to change one thing to make it work again. I updated the download to a plugin so you could easily install that on your WP solution through the plugins panel.
Please let me know if you have any other questions!
Mark says
That’s very kind of you to make it into a plugin.
I was trying to take your code and adapt it to my own needs. You can see my thread on the gravity forums: http://www.gravityhelp.com/forums/topic/different-uses-for-product-field
Is it possible I could help with making that custom box that I want?
Marty Martin says
I’m wanting to add button for a hidden text input with a “Default Value” of “Insert Variable” with it pre-populated with {foobar}. I’ve modified your code at line 51 to be
return sprintf(“{$max_chars}”, $field[“id”], ‘foobar-‘.$field[‘id’] , $field[“type”] . ‘ ‘ . esc_attr($field[‘cssClass’]) . ‘ ‘ . $field[‘size’]);
What do I need to do to get the Default Variable set to “Insert Variable” and the value in GF admin prepopulated to {foobar}?
Thanks!
leonidas says
Hello everyone , i’m new with this plugin and i love it , but i have a problem :
i dont know if it’s possible to add in Gravity form a text field and as the Post’s Author.
Thx
Travis Smith says
Hello Leonidas, Please see Gravity Help for that.
Dave says
Hi, just working my way through this wonderful tutorial as I’m trying to learn how all this works but I have a question that I can’t seem to figure out.
You have chosen to have a large text box, I’m trying to apply this to a standard text field, no more than 15 or 20 characters so I can make it read only (something I would love to have as a check box option, but one problem at a time) but I cannot for the life of me figure out where in the third section (Add the Input Field) the field size is being set. I can see the references to it but no actual size settings. I would love it if you could enlighten me as to how to adjust this please.
Also, and I’m not sure if this is my setup or a WordPress or GForms update or what, but the title described in section 2 (Add the Field Title) will not appear in either your code (I’ve got the latest plugin version) or my tweeked copy of it. Any ideas?
Once again, loving the tutorial, shame on GForms for not doing anything this detailed themselves.
Many Thanks,
Dave.
Dave says
In addition to my question I’ve been playing with it, trying to make it smaller and even if I change the cols and rows it doesn’t affect the displayed box. I’ve tried changing the tags to input and textbox tags, both adjust the size but cause the dynamically populated text to appear to the right of the box for some reason.
I’d really appreciate any help here as I’m tearing my hair out and this is the nearest I’ve found to a workable solution.
Sohag says
Already started coding a custom button. thanks man 🙂
hcg ingredients says
This is the right website for anybody who would like to understand
this topic. You realize so much its almost tough
to argue with you (not that I actually would want to HaHa).
You certainly put a fresh spin on a subject that’s been written about for ages. Excellent stuff, just great!
Phrenks Bloodlust says
Thank you SO MUCH. Incredibly useful, and well-explained. The comments in the code are extremely helpful. The world needs more programmers like you.
Gary says
Hi,
I’m trying to create a custom form field which is like the Drop Down filed which is in Standard Fields.
I managed to create everything, I just can’t figure out how to populate the Choices like the Drop Down has; First Choice, Second Choice…
Any idea?
Thanks,
Gary
whitchcock says
I too and having difficulties populating my custom radio field. Did you ever find a solution to your problem with your Drop Down field?
jose membreno says
Hi, I used your plugin to create this TOS (thanks btw) but I am having a slight issue. In the TOS the appear in the text. See here:
www dot visibilityone dot com/aboutus/referral-agreement/
So the only workaround i could figure out was the following but it still appears at the top and bottom.
See code and text below that I entered on the default value field.
[raw]AFFILIATE REFERRAL FEE AGREEMENT
[/raw]
[raw]THIS Referral FEE AGREEMENT (Agreement) is entered into by and between the referrer (Referrer) and One Inc., a Florida based corporation.
[/raw]
Arnold says
Hi there are using WordPress for your site platform?
I’m new to the blog world but I’m trying to get started and set up
my own. Do you require any coding knowledge to make your own blog?
Any help would be greatly appreciated!
SmartRedFox says
Hello,
First off – thanks for this tutorial, it made it possible to add a limited date field to Gravity forms without completely pulling my hair out!
Just thought I’d post a bit of a gotcha for people adding more than one custom form field though – in your current filter for “gform_field_type_title” you only return something if it matches the “tos” field. This means that all other custom fields get their titles cleared. The way to handle this is to change your function to be like this:
// Adds title to GF custom field
function wps_tos_title( $title, $field_type ) {
if ( $type == ‘tos’ ){
return __( ‘Terms of Service’ , ‘gravityforms’ );
}
else{
return $title;
}
}
Because of the extra parameter you also need to change the filter to be:
add_filter(“gform_field_type_title”, array($this, “wps_tos_title”), 10, 2);
I hope this helps someone.
Thanks,
James
richard says
Tut works great, but is there anyway to make the custom fields compatible with the product price field calculations?
Brandon says
Thanks for the explanation! I tried to download the code with the download link except it gave me a wrong path error?
Axel says
How can i add the conditional logic field, is not appearing on advance tab?
Regards, nice tutorial!
Master Yoshi says
Thanks so much for this great tutorial!
I was able to add a custom field, however I do have a question:
Is it possible to make this use this custom field as conditional for another one? Right now the custom field doesn’t show as a conditional logic field…
Thanks!
Jake says
Hi, the download link is no longer available. Could you rehost it please?
Thanks!
Shashiant says
Thanks so much for this great tutorial!
Any way to add the field setting to “Start Paging” box only. Any JS event handler there for same to hide / show particular field ?
ashokgorigeshok says
http://jsfiddle.net/recv4z16/
I need to show title of the selected item using jQuery dynamically..
I want to show tool tip on the selected item when user mouse over(or) selects the options in the token input button.
if user select on “ABC1” how to show tooltip on in
dragonflyeye says
Any chance you guys could update this post with whatever you’re currently using for code highlighting? It’s very, very difficult to read, otherwise.
Rees says
Excellent Tute, thanks!
Do you know how to output entire form, even with some fields not completed?
Thanks again!
Chris says
How could I disable scroll to bottom? It seems the “Disable Submit Button” does nothing.
Jake Colby says
HI this is the great tutorial thanks a lot for this.
I also want to know that how to import some another plugin function on to gravity form like i create a button for that plugin so how i can add that plugin functionality to that one
Jane Doe says
Hi I followed this tutorial and created a dropdown list instead of the TOS. Everything went well, problem is it isn’t being saved. Not even included when viewed on the form entries. Do you know how to make this work? Thanks!
Tran Ngoc Tuan Anh says
The syntax highlighting seems to be broken on this post. Is the code still working?
pandadvert says
Is there a fresher code to this! As there are newer versions of gravity forms that have been released since then till now.
However i appreciate your golden teachings on this, even though i was unable to create my custom field to work exactly the way i wanted it,
I want to create a simple select field, and that select field will be autopulated with user meta value. I know how to autopulated a user field for a drop down field, but if am working on over 50 forms it will make me to be adding function codes to archive it per form, so i thought creating a field type that already has that function will save me some stress.
Can you be of help please?