Random Fields with Gravity Forms
August 4, 2021: Added support for randomizing the field order.
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.
- How do I install this snippet?
- Do I need to modify this snippet to work with my form?
- What else should I know about this snippet?
- Summary
Stop! There's a better way.
This snippet is available as a plugin with Gravity Perks, a suite of over 47 premium Gravity Forms plugins!
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, 2, array( 1, 2, 4, 5, 7 ), true );
Let me walk you through each of those values and what they represent.
- Update the
123
to the ID of your form. - Update the
2
to the number of random fields you want to show at a time. - Update the
array( 1, 2, 4, 5, 7 )
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. - Lastly, if you want to randomize the order of the fields, update the
true
tofalse
. By default, the field order set in the form editor is preserved. Setting this tofalse
will randomize the field order on load.
To summarize:
new GFRandomFields( $form_id, $display_count, $random_field_ids, $preserve_order );
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.
Summary
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.
Hi, I would like to ask, is it possible to avoid a page being skipped while I used randomizer for this. Everything worked out fine, just that the after page 1, i clicked next, it went straight to page 3 which is the randomizer starts.
Hi Min,
Unfortunately, I am not really tracking the issue you’re reporting. If you have an active Gravity Perks license, can you please submit a support ticket with additional information on the issue and attach an export of the form, so we can look at your setup.
Best,
The two questions in the View Demo link on https://gravitywiz.com/random-fields-with-gravity-forms/ do not get refreshed with new questions when the page is reloaded. I have tried multiple browsers.
The demo link takes me to https://demos.gravitywiz.com/random-fields/
Best Regards
Thanks for pointing this out Dee. The snippet seems to work locally but it doesn’t work on the demo site. I’ll pass this on to our dev team for investigation.
Best,
Hi Dee,
Thanks for the heads-up! It looks like we had too aggressive of caching on that page.
It should be working now.
Hey guys,
Snippet looks to be just what I need, but it is not removing blank pages from my randomised quiz.
The script is working in that I am only seeing 8 questions out of the 15, but the pages with removed questions are still appearing blank.
Is this due to incompatibility with Gravity quiz add-on?
Thanks
Hey Damian, we have a experimental solution for this here: https://github.com/gravitywiz/snippet-library/pull/334
Long term plan is to toughen it up a bit and roll this whole snippet (with the improved support for pages into GP Randomizer).
Hey David,
Thanks for this, although I am having an issue where some times upon refresh the script is calling in a page break ID, I have set “GFRandomFields” as required and 50% of the time is shows just the 8 questions. But sometimes it says 9 questions and one of them is a page break, and I get duplicated “Next page” buttons appear?
Upon close inspection, it is always the final page break ID being called in. Even if I delete page break ID “45”, and create a new one “46” it still gets called in.
Hey Damian, I responded to your comment on the PR as well – given the complicated nature of this configuration, we’d need to ask you to pick up (or upgrade) to an Advanced or Pro license so we can dig in. Hoping that’s doable for you so we can get you sorted!
February 11, 2021: “Also, added support for making all fields random if no field IDs specified.”
Is that the same as shuffling all fields?
For example with X # of fields I’m opening for random order
Form 1
fields = 4,
All fields = 1,2,3,4
new GFRandomFields(1, 4, array(1,2,3,4));
I’ve used this for initialization, but I want 4,2,3,1 or 1,3,4,2 etc I don’t want to exclude fields, but I get everything in order. If i specify 3 fields they stay in order, but the it randomly removes 1.
Above there is a comment about commenting out a line of code. It looks like that code is a little different now, and it doesn’t seem to work to simply comment it out.
suggestion from above:
“
Hi Darin, I think the snippet will work this way if you comment out this line:
add_filter(“gform_form_tag_$form_id”, array(&$this, ‘store_selected_field_ids’));
“
Any suggestion / tips are much appreciated.
Thanks in advance, Joe
Hi Joe,
Currently, the snippet requires the number of fields on the form to be more than the number of fields to display which is why it removes 1. If you have a Gravity Perks License you can get in touch with us via our Support form so we can dig into this further.
Best,
Hi David, your plugin is great but from a few days It seems there’s an issue between your plugin, the latest version of Gravity Forms and the Quiz Add-on. The first PHP error was “Cannot use object of type stdClass as array” at line 82; so I changed it to: if ( in_array( $field->id, $this->all_random_field_ids ) ) { if ( in_array( $field->id, $selected_fields ) ) { $filtered_fields[] = $field; }
Thank you Marco
Hi Marco, the demo is still working as expected which is as much as we can guarantee. If you’re a Gravity Perks customer with and Advanced or Pro license, we’ll be happy to provide support for any snippet via the support form.
Hi David, the issue is caused by the “gform_pre_render” filter, beacuse of a conflict between Gravity Form Quiz Add-on and your snippet, when the “random” option is flagged on the form’s quiz option page. Disabling it everything works fine.
Thanks for your answer but I find it rather odd that you ask me to request assistance through the support of paying customers for a free snippet, which is public and not part of the GravityPerks pack. IMHO you would do well to investigate the issue that I reported to you, because it will surely happen to others too. Have a nice day. Marco
Hi Marco, the snippet is free. Support is not. We can’t guarantee our snippets will work with every possible configuration and add-on available to Gravity Forms but we do guarantee that they will work with core Gravity Forms. The demo is working which confirms that this is still working with core Gravity Forms.
With that said, if enough users are attempting to use the snippet in a specific way and report the same issue, we’ll certainly revisit it. Until then, we hope you can appreciate the hard work we’ve put into this free snippet as-is.
Hey Guys
Great snippet of code. I have an interesting sceneario, where I want to randomize all the questions.
So When I change the last part to new GFRandomFields(2, 3, array(54,55,58)); it stops randomizing, where new GFRandomFields(2, 2, array(54,55,58)); Still randomizes the questions.
How could I change the code to include and randomize the full array?
Hi Hennie, I would expect this to work but unfortunately, I’m a little booked up at the moment. If you’re still having this issue in a week or two, ping me again. ?
Hey,
Is it possible to randomise the order of a ‘rank’ field? We have a survey add-on enabled and are wondering can we randomise the order of answers where the question is- ‘Please rank in order of importance’.
Thanks
I would predict yes but we don’t not have a specific solution for this.
Heya! Great snippet :) We have been looking a way to hide fields that are already answered or prepopulated by url parameters to avoid displaying same questions again and again to our users.
What would be the best approach to get this done? ?
I’d consider allowing a field to check itself in conditional logic via this filter: https://docs.gravityforms.com/gform_conditional_logic_fields/
Just what I was looking for
One question is there a way to shuffle the question order so every time the page is refreshed the order changes?
Example first page view order 1, 2, 3, 4
Second page view 4, 2, 3 1
This would solve the problem I am facing.
Thank you for the snippet and your help
Hi Darin, I think the snippet will work this way if you comment out this line:
add_filter("gform_form_tag_$form_id", array(&$this, 'store_selected_field_ids'));
Great piece of code.
Can I ask some help please? I have 2 sets of questions that need to be random in the same form. 10 questions per set, only need 1 per set answered in teh same form.
new GFRandomFields(4, 2, array(45,54,53,52,51,50,49,48,47,46,69,78,77,76,75,74,73,72,71,70));
I have tried using a page break in between the 2 sets of questions, but sometimes on the first page 2 questions from the first set of 10 questions are displayed.
Any idea on how I can maybe handle this?
Again, great piece of code!
Hi Grobbie, it looks like the issue is in the store_selected_field_ids() method. It adds an <hinput> to the form which stores the randomly selected fields. The problem is that this <hinput> is generic so creating multiple instances of the class will override the previously set values. This is something I’d be happy to enhance via support (support is available to Gravity Perks license-holders).
This is great but I seem to be getting an error:
Warning: Invalid argument supplied for foreach()
It seems to relate to this line of code:
foreach($keys as $key) { $field_ids[] = $this->all_random_field_ids[$key]; }
Any ideas how to resolve please?
Hi,
I just posted a comment that seemed to not show (I guess pending moderation). But after some googling I managed to get the code to work again after changing line 79 as per the code below and it seems to work a treat now….
Prior to that I was getting an invalid argument for foreach.
Tom
Hi Tom, based on your fix it would seem that something may have been wrong with your configuration. Were you passing the field IDs as an array? Could you share your configuration with me?
Hi David, Not that I am aware. I simply setup the form as a quiz and kept everything at the default settings. All still working fine now though.
Hi David, Not that I am aware. I simply setup the form as a quiz and kept everything at the default settings. All still working fine now though.
Wow.. This just saved me.. THANK YOU! Worked great.
Glad to help, Brian!
Hi, thanks for the code. Is it possible to randomize the field (one question) not at every page reload but one for day. I want to show one different question every day in a range of ten days randomly excluding field already chosen in previous days.
Thanks
This is possible but would require modifying the existing snippet. The idea is that you would cache the results and then expire that cache every 24 hours or by determining how many hours are between the time the cache is created and midnight of the current day.
When i submitted the form i got the error Warning: Creating default object from empty value in /home/hotnsourmv/public_html/wp-content/plugins/gravityformsquiz/class-gf-quiz.php on line 1127
Warning: Creating default object from empty value in /home/hotnsourmv/public_html/wp-content/plugins/gravityformsquiz/class-gf-quiz.php on line 1127
Fatal error: Cannot use object of type stdClass as array in /home/hotnsourmv/public_html/wp-content/themes/betheme-child/functions.php on line 400
Hi Kiran, sorry for the super slow response. Could you send me an export of your form?
I’m getting this error when trying to use it:
Warning: Invalid argument supplied for foreach() in /home/oreopr/public_html/site/wp-content/themes/dms/dms/functions.php on line 96
Warning: Invalid argument supplied for foreach() in /home/oreopr/public_html/site/wp-content/themes/dms/dms/functions.php on line 96
Hi Yamil, sorry for the super slow response. Could you send me an export of your form?
I have enabled the snippet to work correctly on my site, but since I have a multi page step Quiz. It still displays the question with no answer as well as the progress bar shows 1 of 10, When I have only chosen 5 fields to show from the array params
Do you have a URL where I could view your form? Also, could you post your exact configuration of the snippet?
David, Below is the url to test.
Test Url
And here is the code I used for the array of fields.
new GFRandomFields(1, 5, array(1,2,3,25,26,27,28,29,30,31)); Form ID: 1, Number of questions to show: 5, Pick from Array of 10 questions The Correct answer for each questions is always 1
Can you send me an export of your form? I’ll try to recreate this locally.
Here is the export. Export Form
Thanks for the export. I was able to recreate the issue. After re-familiarizing myself with the code (I wrote this snippet a while go), I realized that they way you’re using this just isn’t supported by the code. Right now the multi-page support is spotty because it doesn’t guarantee that there will be at least one field on each page. Rather, it selects the random fields on the first page and then if the field is present on subsequent pages it will appear.
Would you be interested in commissioning better multi-page support? If so, get in touch.
I’m getting this error when I have have WP_DEBUG enabled:
Strict Standards: Accessing static property GFRandomFields::$all_random_field_ids as non static in /srv/www/calton.dev/current/web/app/themes/calton/lib/g_forms.php on line 11
Strict Standards: Accessing static property GFRandomFields::$display_count as non static in /srv/www/calton.dev/current/web/app/themes/calton/lib/g_forms.php on line 12
Warning: Cannot modify header information - headers already sent by (output started at /srv/www/calton.dev/current/web/app/themes/calton/lib/g_forms.php:11) in /srv/www/calton.dev/current/web/wp/wp-includes/pluggable.php on line 1178
g_forms.php is being included in functions.php (the include works fine)
Line 11 can be seen here: http://pastebin.com/gc4HbKPe
By the way, with WP_DEBUG turned off, it randomizes just fine, I’m just trying to clear up errors.
Thanks, Brandon. These issues should now be fixed.
David, Have you been able to get this function to work properly, using multi-page forms? I’m trying to get it to work on one of my sites, with no luck.
David, Are you aware that the demo page (https://gravitywiz.com/demos/random-fields/) isn’t functioning as it should? The same fields are always displayed (at least that’s what I see, with two different browsers.).
Thanks, Ed
I should have added that the snippet works perfectly, on my site. I’ve been looking for this functionality, for years.
Glad to hear your search has ended! Thanks for comment.
Thanks for the heads up, Ed. I’ve contacted my host about excluding this page from the cache. I’ll let you know once it’s done.
Apparently, my host is on fire today. Fixed!
Hi,
I understand that I need to add the code to my existing functions.php of my theme (which already have sevezral functions, then I need to remove the “<? php” at the beginning), but I don’t understand/see what I need to put in a page to display this random entry of a form. Thanks!
Hi Thomas, once you’ve configured the snippet based on your requirements, it should just work. If you’d like to included the contents of your theme’s functions.php file in a pastie and provide a URL where I can preview your form, I’d be happy to see if I can see any obvious issues.
David,
Thank you for your quick reply. In fact, I understood my mistake. I’m looking for a way to display a random result of my form while your snippet display the form to fill. I created tons of questions for a quiz game and then I’m looking for a way to display one of the question and the associated answer randomly. I’m using GF Directory, but it display all the entries or one, but you can’t sort them randomly. Anyway, thank you very much for providing such code, even if it’s not for me :)
With regards Kevin Hughes, the WSOD occurs because on line 31 the double quotes need to be escaped e.g.
$input = "";
Then it does still seem to work with the latest version of GF and the quiz add on.
Thanks, Dunk. I’ve updated the snippet to address this issue.
This no longer appears to work:
– When I install the snippet, WordPress throws me a WSOD
It’s been a while since you posted but I made a fix that should resolve your issue. See the latest code above.
I don’t get it to work. When debugging the code this: add_filter(“gform_validation_$form_id”, array(&$this, ‘validate’)); is the last code part from the snippet to be utilised, the function: pre_render($form) { is never called.
Very useful, as always! Â I can and will use this a lot.
One question: If I want to have multiple forms on my site perform this random question feature, do I just need to add anotherÂ
new
GFRandomFields(12, 2,
array
(1,2,3,4,5));
in functions.php but change out the form_id, display_count, and random_field_ids?Thanks for posting.
That’s right! I haven’t tested this with multiple forms, but I don’t foresee any issues. Let me know how it goes. :)