February 11, 2021: Added support for saving selected random fields in the entry meta. Also, added support for making all fields random if no field IDs specified.
November 26, 2020: Added support for skipping pages on mulit-page forms where no random fields were visible.
May 18th, 2017: Added support for creating multiple random field groups on a single form. Add form export to support testing with base configuration.
March 17, 2015: Fixed strict standards issues with class properties.
September 17, 2014: Fixed issue where $input string was not properly escaped.
This snippet provides an easy way to show a random number of fields on your Gravity Forms. Let’s say you’re using Gravity Forms to power a simple questionnaire. You have five questions total but only want to show three of those questions per submission. This snippet lets you do that!
How do I install this snippet?
Just copy and paste the code into your theme’s functions.php file.
Do I need to modify this snippet to work with my form?
Yes! This snippet is a little different than some of the other snippets on the site. After you’ve installed the snippet, you can initialize it like this:
new GFRandomFields( 123, 3, array( 1, 2, 3, 4, 5 ) );
Let me walk you through each of those values and what they represent.
- Update the
123to the ID of your form.
- Update the
3to the number of random fields you want to show at a time.
- Lastly, update the
array( 1, 2, 3, 4, 5 )to the field IDs which should be random. Any field ID you do not include in this array will considered a “static” field and show up on every form load.
new GFRandomFields( $form_id, $display_count, $random_field_ids );
What else should I know about this snippet?
Oh, boy. Lots!
- Field validation is skipped for any random field that is not selected for display.
- It works with multi-page forms such that after the first page is submitted, the randomly selected fields will remain the same until the form is submitted (or refreshed).
- Also on multi-page forms, if a page has no fields visible, the page will be skipped.
- It integrates with Save & Continue so if you return later to complete your submission, the randomly selected fields are preserved.
Make sure you check out the demo to see this snippet in action. Let us know in the comments if you’d like to see this become part of our Gravity Perks suite.