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.

  1. How do I install this snippet?
  2. Do I need to modify this snippet to work with my form?
  3. What else should I know about this snippet?
  4. 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!

View Plugin Buy Gravity Perks

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.

  1. Update the 123 to the ID of your form.
  2. Update the 2 to the number of random fields you want to show at a time.
  3. 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.
  4. Lastly, if you want to randomize the order of the fields, update the true to false. By default, the field order set in the form editor is preserved. Setting this to false 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.

Comments

  1. Min Hong
    Min Hong February 13, 2024 at 12:12 am

    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.

    Reply
    1. Samuel Bassah
      Samuel Bassah Staff February 14, 2024 at 5:25 am

      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,

    1. Dario
      Dario August 7, 2023 at 1:39 pm

      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,

    2. Clay Griffiths
      Clay Griffiths Staff August 9, 2023 at 11:06 am

      Hi Dee,

      Thanks for the heads-up! It looks like we had too aggressive of caching on that page.

      It should be working now.

  2. Damian Smith
    Damian Smith February 10, 2023 at 4:50 am

    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

    Reply
    1. Damian Smith
      Damian Smith May 26, 2023 at 7:34 am

      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?

    2. Damian Smith
      Damian Smith May 26, 2023 at 7:37 am

      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.

    3. David Smith
      David Smith Staff May 26, 2023 at 9:47 pm

      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!

  3. Joe Davis
    Joe Davis June 23, 2021 at 2:23 pm

    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

    Reply
    1. Samuel Bassah
      Samuel Bassah Staff June 23, 2021 at 4:27 pm

      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,

  4. marco
    marco October 2, 2019 at 6:44 pm

    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; }

    http://snippi.com/s/5veohq2 Then started errors on GF core files, on not existing methods or using arrays as objects. If I disable the Quiz Add-on or your plugin, everything works fine. Do you have any suggestions, please?

    Thank you Marco

    Reply
    1. David Smith
      David Smith Staff October 3, 2019 at 12:01 pm

      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.

    2. Marco
      Marco October 4, 2019 at 8:54 am

      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

    3. David Smith
      David Smith Staff October 4, 2019 at 12:31 pm

      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.

  5. Hennie
    Hennie June 24, 2019 at 4:48 am

    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?

    Reply
    1. David Smith
      David Smith Staff June 27, 2019 at 2:00 pm

      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. ?

  6. Mark O Leary
    Mark O Leary October 19, 2018 at 11:59 am

    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

    Reply
  7. Laz
    Laz October 14, 2018 at 8:40 am

    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? ?

    Reply
  8. Darin Densley
    Darin Densley June 17, 2018 at 12:53 pm

    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

    Reply
    1. David Smith
      David Smith Staff June 20, 2018 at 8:14 am

      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'));

  9. Grobbie
    Grobbie February 6, 2017 at 6:24 am

    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!

    Reply
    1. David Smith
      David Smith Staff February 6, 2017 at 9:27 am

      Hi Grobbie, it looks like the issue is in the store_selected_field_ids() method. It adds an &lthinput> to the form which stores the randomly selected fields. The problem is that this &lthinput> 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).

  10. Tom Hodgson
    Tom Hodgson December 12, 2016 at 5:03 am

    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?

    Reply
    1. Tom Hodgson
      Tom Hodgson December 12, 2016 at 5:44 am

      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

    2. David Smith
      David Smith Staff December 19, 2016 at 10:30 pm

      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?

    3. Tom Hodgson
      Tom Hodgson December 21, 2016 at 4:24 am

      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.

    4. Tom Hodgson
      Tom Hodgson December 21, 2016 at 4:24 am

      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.

  11. lestatu2
    lestatu2 September 30, 2016 at 11:15 am

    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

    Reply
    1. David Smith
      David Smith Staff September 30, 2016 at 11:27 am

      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.

  12. kiran correya
    kiran correya May 14, 2016 at 3:52 am

    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

    Reply
    1. David Smith
      David Smith Staff July 1, 2016 at 9:12 pm

      Hi Kiran, sorry for the super slow response. Could you send me an export of your form?

  13. Yamil Alvarez
    Yamil Alvarez May 13, 2016 at 12:07 am

    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

    Reply
    1. David Smith
      David Smith Staff July 1, 2016 at 9:12 pm

      Hi Yamil, sorry for the super slow response. Could you send me an export of your form?

  14. Gabriel
    Gabriel July 17, 2015 at 12:01 pm

    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

    Reply
    1. David Smith
      David Smith Staff July 20, 2015 at 9:42 pm

      Do you have a URL where I could view your form? Also, could you post your exact configuration of the snippet?

    2. Gabriel
      Gabriel July 21, 2015 at 12:46 pm

      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

    3. David Smith
      David Smith Staff July 23, 2015 at 8:56 am

      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.

  15. Brandon Shutter
    Brandon Shutter March 15, 2015 at 11:39 pm

    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.

    Reply
  16. Ed Coyne
    Ed Coyne December 10, 2014 at 12:29 pm

    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.

    Reply
    1. Ed Coyne
      Ed Coyne November 15, 2014 at 3:22 am

      I should have added that the snippet works perfectly, on my site. I’ve been looking for this functionality, for years.

    2. David Smith
      David Smith Staff November 17, 2014 at 10:05 am

      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.

  17. Thomas
    Thomas September 20, 2014 at 6:06 am

    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!

    Reply
    1. David Smith
      David Smith Staff September 20, 2014 at 10:07 am

      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.

    2. Thomas
      Thomas September 20, 2014 at 4:46 pm

      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 :)

  18. Dunk
    Dunk September 17, 2014 at 4:12 am

    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.

    Reply
  19. Kevin Hughes
    Kevin Hughes February 4, 2014 at 1:01 pm

    This no longer appears to work:

    – The demo above does not randomize
    – When I install the snippet, WordPress throws me a WSOD
    Reply
    1. David Smith
      David Smith Staff September 17, 2014 at 11:32 pm

      It’s been a while since you posted but I made a fix that should resolve your issue. See the latest code above.

  20. Herman
    Herman May 28, 2013 at 11:37 pm

    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.

    Reply
  21. Shawn Hunter
    Shawn Hunter July 21, 2012 at 5:50 pm

    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 newGFRandomFields(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.

    Reply
    1. David Smith
      David Smith Staff July 23, 2012 at 10:01 am

      That’s right! I haven’t tested this with multiple forms, but I don’t foresee any issues. Let me know how it goes. :)

Leave a Reply

Your email address will not be published. Required fields are marked *

  • Trouble installing this snippet? See our troubleshooting tips.
  • Need to include code? Create a gist and link to it in your comment.
  • Reporting a bug? Provide a URL where this issue can be recreated.

By commenting, I understand that I may receive emails related to Gravity Wiz and can unsubscribe at any time.

Download Snippet

Random Fields with Gravity Forms

This field is for validation purposes and should be left unchanged.