Gravity Varieties is among the strongest contact kinds in the marketplace right now for WordPress web sites. Simple to make use of, feature-rich, and able to combine with advertising and marketing CRMs – Gravity Varieties has so much going for it. As a WordPress developer, I like Gravity Forms due to its complete and very well-documented implementation of motion hooks and filters, which let you lengthen the performance and simply modify the content material and exercise of Gravity Varieties.
Need to uncover how Gravity Varieties hooks and filters can revitalize your web site? Pull up your favourite cup of joe, and let’s dive in.
Widespread Makes use of for Gravity Varieties Hooks and Filters
What are among the frequent use-cases I take advantage of Gravity Varieties hooks and filters for?
- Enqueueing Custom Scripts
- Adding Custom Validation
- Custom Honeypot Fields With ADA Support
- Checkbox To Toggle Field
Enqueueing Customized Scripts
Gravity Varieties presents a hook to embed scripts and types on the pages the place your kinds seem. I could use this so as to add customized options like an AJAX lookup to populate a listing subject or so as to add form-specific types. Gravity Varieties has us coated.
The essential syntax for loading scripts and types through Gravity Varieties appears like this:
add_action( 'gform_enqueue_scripts', ‘your_function_name’, 10, 2 );
The above code will load scripts on all of your pages containing a Gravity Kind. Gravity Varieties additionally presents the power to focus on a selected type by form_id. To do that, you append the id to the top of the primary parameter within the motion name as proven beneath:
add_action( 'gform_enqueue_scripts_1', ‘your_function_name’, 10, 2 );
Within the code above, the shape with id 1 is being focused. Scripts enqueued in your perform will solely load for type 1.
A full implementation could look one thing like this:
$registration_form_id = 1; add_action( “gform_enqueue_scripts_$registration_form_id”, 'gform_enqueue_scripts_registration_form', 10, 2 ); perform gform_enqueue_scripts_registration_form( $type, $is_ajax ) wp_enqueue_style( 'registration-form', '/dist/css/registration-form.css', array(), false, 'all' ); wp_enqueue_script( 'custom_script', 'dist/js/registration-form.js', array( ‘jquery’ ), false, false );
We begin by specifying the shape id in a variable so we will reuse this with different hooks and filters. Doing this additionally makes it straightforward to repeat and reuse this block of code or convert it into a category.
If the web page we’re loading has the shape with id = 1, then it’ll load the scripts. It’s that straightforward!
Serious about studying extra? Try Gravity Varieties documentation on gform_enqueue_scripts.
Including Customized Validation
Generally, a subject must be validated for a selected want. Usually I take advantage of this to restrict the choices customers could make in a subject. For instance, I’ve used this characteristic to make sure that specific zip codes are blocked, customized date ranges are used, and even to confirm that customized put up kind (CPT) names haven’t been beforehand used when creating CPT from a type entry.
Gravity Varieties presents validation with the next filter hooks:
gform_validation is used whenever you need to course of a number of type fields at a time – all the type.
gform_field_validation is used whenever you need to goal a single subject.
The implementation is totally different for every. We’ll begin with a quick instance of gform_validation.
Like the instance above, you possibly can goal all kinds, or by appending the shape id, you possibly can goal a single type:
add_filter( 'gform_field_validation', 'your_function_name', 10, 4 ); // The next declaration targets all fields in type 1 add_filter( 'gform_field_validation_1’, 'your_function_name', 10, 5 );
For instance, let’s use the validation to make sure a variety of postal codes can’t be submitted with the shape. First, we are going to label our zip/postal code subject to reference it in our code later. From the Gravity Kind edit display, click on on the tackle subject and click on ” Superior ” in the best sidebar. Mark the checkbox titled, “Enable subject to be populated dynamically,” add then add the label “postal_code” for the “ZIP / Postal Code” subject as proven beneath.
Subsequent, we add our customized validation script:
perform gform_field_validation_block_zip_codes( $validation_result ) $form_id = 2; $type = GFAPI::get_form( $form_id ); $entry = GFFormsModel::get_current_lead(); $blocked_postal_codes = array( '12345', '23456', '34567', ); $postal_code=""; foreach( $type['fields'] as &$subject ) if ( 'tackle' == $field->kind ) // Get the enter key for the zip/postal_code subject $inputs = $field->inputs; $labels = wp_list_pluck( $inputs, 'identify' ); $key = array_search( "postal_code", $labels ); $input_key = $inputs[$key]['id']; // Get present worth $postal_code = rgar( $entry, $input_key ); // block stuff if ( in_array( $postal_code, $blocked_postal_codes ) ) $field->failed_validation = true; $field->validation_message = __('We can not ship to this postal code!', 'oyova'); $validation_result['form'] = $type; return $validation_result;
Whilst you can hardcode the entry fields into the validation script, we present above how one can lookup the sphere by the label we entered. If Gravity Varieties have been ever to alter its construction, this may be certain that the lookup nonetheless grabs the proper subject entry.
We additionally need to level out that the instance above demonstrates how one can set your customized validation messages on failure.
$field->validation_message = __('We can not ship to this postal code!', 'oyova');
Subsequent is the field-specific hook, gform_field_validation. This hook means that you can goal a single subject and passes all the info you want into the perform, and it tends to be simpler to work with. The decision appears like this:
add_filter( 'gform_field_validation_1_2', 'your_custom_validation', 10, 4 );
The primary quantity – 1 – is the shape id, and the second quantity – 2 – is the sphere id you might be focusing on. Let’s modify the code above to make use of this filter as an alternative. The change will appear like this:
$form_id = 2; $field_id = 4; // Deal with subject group add_filter( "gform_field_validation_$form_id_$field_id", 'gform_field_validation_address_field', 10, 4 ); perform gform_field_validation_address_field( $consequence, $worth, $type, $subject ) $blocked_postal_codes = array( '12345', '23456', '34567', ); $inputs = $field->inputs; $labels = wp_list_pluck( $inputs, 'identify' ); $key = array_search( "postal_code", $labels ); $input_key = $inputs[$key]['id']; // Get present worth $postal_code = rgar( $worth, $input_key ); // block stuff if ( in_array( $postal_code, $blocked_postal_codes ) ) $consequence['is_valid'] = false; $consequence['message'] = __('We can not ship to this postal code!', 'oyova'); return $consequence;
Right here we specify the precise type and subject we are going to validate. $result’s an associative array that tracks two values: 1) is the sphere legitimate – true/false, 2) a selected error message. $worth accommodates all the subject’s enter values. Since we’re working with an tackle subject, it contains 5 sub-field inputs (Deal with Line 1, Deal with Line 2, Metropolis, State, Zip / Postal Code). All of those enter fields’ values are handed as an associative array in $worth. $type passes all the type object. $subject passes the sphere object we’re working with.
Gaining access to the $consequence, $worth, and $subject parameters make it a snap programmatically to seek out the enter subject key we want. Then we seize the worth entered and see if it was one among our forbidden zip / postal codes. In that case, we set the $consequence[is_valid] state to false and may specify a message for the person.
It’s faster to focus on a selected subject enter and arrange customized validation utilizing this technique.
Customized Honeypot Fields With ADA Help
Out of the field, Gravity Varieties has a honeypot resolution. Just lately, nonetheless, a lot of our shoppers have been receiving spam as bots have discovered how one can keep away from the honeypot subject. I attribute this to the truth that “honeypot” seems within the code base. My resolution is to create a hidden checkbox subject labeled “Expedited Response Requested.” The difficulty with this strategy is that the sphere remains to be accessible through tabbing, which we don’t need, and is seen to display readers, which we don’t need. To repair this we have to modify the sphere output and add
aria-hidden="true" for screenreaders, and
tabindex="-1" to disable tabbing to the sphere. How will we obtain this?
Enter in Gravity Kind’s subject content material filter:
// Run filter on all from fields add_filter( 'gform_field_content', 'my_custom_function', 10, 5 ); // Run filter on all fields in type 3 add_filter( 'gform_field_content_3', 'my_custom_function', 10, 5 ); // Run filter on type 3, subject with id = 1 add_filter( 'gform_field_content_3_1', 'my_custom_function', 10, 5 );
We are going to use the final filter to focus on the precise subject for our functions and insert the wanted html code. Right here is the code snippet to do that:
$form_id = 3; $field_id = 5; // Deal with subject group add_filter( “gform_field_content_$form_id_$field_id”, 'honeypot_html_filter', 10, 5 ); perform honeypot_html_filter( $content material, $subject, $worth, $lead_id, $form_id ) if ( str_contains( $field->cssClass, 'screenreader-hide' ) ) $content material = str_replace( '<enter','<enter aria-hidden="true" tabindex="-1"', $content material ); return $content material;
The filter passes us the HTML output for the shape subject. A easy PHP str_replace() permits us to switch the enter subject, including the required lacking code:
You might have observed that the
gform_field_content filter passes 5 variables. With these 5 parameters being handed it’s doable to utterly rewrite the HTML output for a subject. In our final instance, we’ll have a look at changing a easy checkbox right into a toggle swap, combining among the filters we now have used above.
Checkbox To Toggle Discipline
Let’s convert a checkbox to a toggle subject utilizing two of the filters above. Whereas it’s doable to obtain plugins with this characteristic or program your individual toggle fields with Gravity Kind’s API library, this can be a faster route to attain the identical end result. Our course of can have three components:
- Set up the form field in Gravity Forms
- Enqueue the styles we need to make the field look like a toggle
- Use the field content filter to modify the HTML output
Arrange the shape subject in Gravity Varieties
Our easy toggle will work with one checkbox subject. When the checkbox is checked, the shape will submit “On.” First, create one checkbox labeled “On”:
For our stylesheet and customized content material to know which subject(s) to switch, we’re going to set a customized class of “toggle-field” below the “Look” tab. Your settings ought to appear like this:
Now that we now have the essential setup, let’s get coding.
We have to add a couple of types to our checkbox subject to turn out to be a toggle, and we’ll try this now earlier than we edit the sphere. Right here is our enqueue stylesheet code:
$form_id = 2; add_action( "gform_enqueue_scripts_$form_id", 'gform_enqueue_scripts_contact_form', 10, 2 ); perform gform_enqueue_scripts_contact_form( $type, $is_ajax ) wp_enqueue_style( 'contact-form', 'url/to/stylesheet/form_2.css', array(), false, 'all' );
The contents of form_2.css:
/* Kind 2 - Contact Kind - Customized Kinds */ .toggle cursor: pointer; show: inline-block; .toggle-switch show: inline-block; background: #cf4242; border-radius: 16px; width: 58px; top: 32px; place: relative; vertical-align: center; transition: background 0.25s; .toggle-switch:earlier than, .toggle-switch:after content material: ""; .toggle-switch:earlier than show: block; background: linear-gradient(to backside, #fff 0%, #eee 100%); border-radius: 50%; box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.25); width: 24px; top: 24px; place: absolute; prime: 4px; left: 4px; transition: left 0.25s; .toggle:hover .toggle-switch:earlier than background: linear-gradient(to backside, #fff 0%, #fff 100%); box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.5); .toggle-checkbox:checked + .toggle-switch background: #62c071; .toggle-checkbox:checked + .toggle-switch:earlier than left: 30px; .toggle-checkbox place: absolute; visibility: hidden; .toggle-label margin-left: 5px; place: relative; prime: 2px;
Now that we’ve bought the types prepared let’s add that html markup to rework our checkbox right into a toggle.
Use the sphere content material filter to switch the html output
The toggle subject wants a deal with to maneuver forwards and backwards. We’ll add that. We’ll additionally wrap our enter subject and the toggle parts inside a label aspect, which signifies that wherever we click on on the toggle, it’ll examine/uncheck the hidden checkbox and animate the toggle swap. Right here’s the code:
add_filter( "gform_field_content_$form_id", 'oyo_toggle_fields', 10, 5 ); perform oyo_toggle_fields( $content material, $subject, $worth, $lead_id, $form_id ) if ( str_contains( $field->cssClass, 'toggle-field' ) ) $field_id = $field->id; $decisions = $field->decisions; $label = $decisions['text'] ?? 'On'; $content material=" <legend class="gfield_label gform-field-label gfield_label_before_complex">Toggle</legend> <div class="ginput_container ginput_container_checkbox toggle-container"> <div class="gfield_checkbox" id="input_".$form_id.'_'.$field_id.'"> <div class="gchoice gchoice_'.$form_id.'_'.$field_id.'_1"> <label class="input-label toggle"> <enter class="gfield-choice-input product-chbx toggle-checkbox" identify="input_'.$field_id.'.1" kind="checkbox" worth="On" id="choice_'.$form_id.'_'.$field_id.'_1"> <div class="toggle-switch"></div> <span class="toggle-label">'.$label.'</span> </label> </div> </div> </div>'; return $content material;
Within the code above, we’re utilizing the gform_field_content filter on our type and focusing on all the type fields. We search by way of all of the fields, and if any of them have the category we set earlier, “toggle-field,” thenthat subject’s HTML will probably be changed with the code above.
Subsequent, we dynamically render the label subsequent to the toggle. We seize all the of the sphere’s decisions (enter fields) – these are the checkbox enter fields. Then we parse that array for the related label, which can turn out to be our toggle label:
$decisions = $field->decisions; $label = $decisions['text'] ?? 'On';
In case you have not used “On” however another textual content, the block of code above will seize what you used.
Subsequent, we use the default Gravity Varieties output till we insert our label aspect. At this level, we add all the parts we have to make a toggle:
<label class="input-label toggle"> <enter class="gfield-choice-input product-chbx toggle-checkbox" identify="input_'.$field_id.'.1" kind="checkbox" worth="On" id="choice_'.$form_id.'_'.$field_id.'_1"> <div class="toggle-switch"></div> <span class="toggle-label">'.$label.'</span> </label>
This converts our bland checkbox into a shocking toggle swap:
Getting the Most Out of Gravity Varieties Filters & Motion Hooks
Whereas we’ve proven a couple of examples of Gravity Varieties filters and motion hooks, we’ve solely barely scratched the floor. There are extra hooks to switch the show of kinds on the front-end and back-end, to switch submission outcomes earlier than they’re saved, to change the e-mail (affirmation) outcomes, to alter the thanks web page, and even hooks which might be run after type submissions have been accomplished.
Need extra info? Try Gravity Varieties info on Action Hooks and Filters.
All of those hooks make Gravity Varieties a strong device when desirous to work with a type builder however nonetheless be capable to modify all elements of the HTML output and performance that the plugin presents.
In case you are working with Gravity Varieties and need assistance modifying your type, including customized fields, and even integrating it with third-party purposes, then know that our consultants at Oyova are right here that can assist you get the job executed with our internet growth providers.