The gform_pre_validation filter in Gravity Forms allows you to manipulate the Form Object during the form validation process.
Usage
add_filter('gform_pre_validation', 'your_function_name');
For a specific form, append the form ID to the hook name:
add_filter('gform_pre_validation_6', 'your_function_name');
Parameters
$form
(Form Object): The current form to be filtered.
More information
See Gravity Forms Docs: gform_pre_validation
Examples
Conditionally Required Field
Make a field required based on the value of another field:
add_filter('gform_pre_render', 'gw_conditional_requirement'); add_filter('gform_pre_validation', 'gw_conditional_requirement'); function gw_conditional_requirement($form) { $value = rgpost('input_2'); if ($value == 'no') { return $form; } foreach ($form['fields'] as &$field) { if ($field->id == 1) { $field->isRequired = true; } } return $form; }
Populate Choices – Drop Down
Dynamically populate a drop-down field with posts from the “Business” category:
add_filter('gform_pre_validation', 'populate_dropdown'); function populate_dropdown($form) { if ($form['id'] != 5) { return $form; } $posts = get_posts('category=' . get_cat_ID('Business')); $items = array(); $items[] = array('text' => '', 'value' => ''); foreach ($posts as $post) { $items[] = array('value' => $post->post_title, 'text' => $post->post_title); } foreach ($form['fields'] as &$field) { if ($field->id == 8) { $field->choices = $items; } } return $form; }
Dynamically add a reCAPTCHA field to all forms
Add reCAPTCHA to all your forms dynamically:
add_filter('gform_pre_render', 'add_captcha_field'); add_filter('gform_pre_validation', 'add_captcha_field'); function add_captcha_field($form) { if (empty($form['fields']) || !is_array($form['fields'])) { return $form; } $page_number = 1; $has_captcha_field = false; foreach ($form['fields'] as $field) { if ($field->type == 'captcha') { $has_captcha_field = true; } if ($field->type == 'page') { $page_number++; } } if (!$has_captcha_field) { $form['fields'][] = GF_Fields::create(array( 'type' => 'captcha', 'id' => GFFormsModel::get_next_field_id($form['fields']), 'label' => 'Captcha', 'displayOnly' => true, 'formId' => $form['id'], 'pageNumber' => $page_number, 'visibility' => 'visible', )); } return $form; }
Place this code in the functions.php
file of your active theme.