Skip to content

Instantly share code, notes, and snippets.

@spivurno
Last active November 26, 2020 13:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spivurno/3708723 to your computer and use it in GitHub Desktop.
Save spivurno/3708723 to your computer and use it in GitHub Desktop.
Gravity Wiz // Gravity Forms // Random Field Order
<?php
/**
* WARNING! THIS SNIPPET MAY BE OUTDATED.
* The latest version of this snippet can be found in the Gravity Wiz Snippet Library:
* https://github.com/gravitywiz/snippet-library/blob/master/gravity-forms/gw-random-fields.php
*/
/**
* Gravity Wiz // Gravity Forms // Random Fields
*
* Randomly display a specified number of fields on your form.
*
* @version 1.1
* @author David Smith <david@gravitywiz.com>
* @license GPL-2.0+
* @link https://gravitywiz.com/random-fields-with-gravity-forms/
*
* Plugin Name: Gravity Forms Random Fields
* Plugin URI: https://gravitywiz.com/random-fields-with-gravity-forms/
* Description: Randomly display a specified number of fields on your form.
* Author: Gravity Wiz
* Version: 1.1
* Author URI: http://gravitywiz.com
*/
class GFRandomFields {
public $all_random_field_ids;
public $display_count;
public $selected_field_ids = array();
public function __construct( $form_id, $display_count = 5, $random_field_ids = false ) {
$this->_form_id = $form_id;
$this->all_random_field_ids = (array) $random_field_ids;
$this->display_count = $display_count;
add_filter( "gform_pre_render_$form_id", array( $this, 'pre_render' ) );
add_filter( "gform_form_tag_$form_id", array( $this, 'store_selected_field_ids' ) );
add_filter( "gform_validation_$form_id", array( $this, 'validate' ) );
add_filter( "gform_pre_submission_filter_$form_id", array( $this, 'pre_render' ) );
//add_filter( "gform_admin_pre_render_$form_id", array( $this, 'admin_pre_render' ) );
//add_action( 'gform_entry_created', array( $this, 'save_selected_field_ids_meta' ), 10, 2 );
}
public function pre_render( $form ) {
return $this->filter_form_fields( $form, $this->get_selected_field_ids() );
}
public function admin_pre_render( $form ) {
if ( $form['id'] != $this->_form_id ) {
return $form;
}
return $form;
}
public function store_selected_field_ids( $form_tag ) {
$hash = $this->get_selected_field_ids_hash();
$value = implode( ',', $this->get_selected_field_ids() );
$input = sprintf( '<input type="hidden" value="%s" name="gfrf_field_ids_%s">', $value, $hash );
return $form_tag . $input;
}
public function validate( $validation_result ) {
$validation_result['form'] = $this->filter_form_fields( $validation_result['form'], $this->get_selected_field_ids() );
$validation_result['is_valid'] = true;
foreach ( $validation_result['form']['fields'] as $field ) {
if ( $field['failed_validation'] ) {
$validation_result['is_valid'] = false;
}
}
return $validation_result;
}
public function filter_form_fields( $form, $selected_fields ) {
$filtered_fields = array();
foreach ( $form['fields'] as $field ) {
if ( in_array( $field['id'], $this->all_random_field_ids ) ) {
if ( in_array( $field['id'], $selected_fields ) ) {
$filtered_fields[] = $field;
}
} else {
$filtered_fields[] = $field;
}
}
$form['fields'] = $filtered_fields;
return $form;
}
public function get_selected_field_ids( $entry_id = false ) {
// check if class has already init fields
if ( !empty( $this->selected_field_ids ) ) {
return $this->selected_field_ids;
}
$hash = $this->get_selected_field_ids_hash();
// If entry ID is passed, retrieve selected fields IDs from entry meta.
if ( $entry_id ) {
$field_ids = gform_get_meta( $entry_id, "_gfrf_field_ids_{$hash}" );
return is_array( $field_ids ) ? $field_ids : array();
}
// Check if fields have been submitted.
$field_ids = rgpost( "gfrf_field_ids_{$hash}" );
if ( !empty( $field_ids ) ) {
return explode( ',', $field_ids );
}
$field_ids = array();
$keys = array_rand( $this->all_random_field_ids, $this->display_count );
if ( !is_array( $keys ) ) {
$keys = array( $keys );
}
foreach ( $keys as $key ) {
$field_ids[] = $this->all_random_field_ids[$key];
}
$this->selected_field_ids = $field_ids;
return $field_ids;
}
public function get_selected_field_ids_hash() {
return wp_hash( implode( '_', $this->all_random_field_ids ) );
}
public function save_selected_field_ids_meta( $entry, $form ) {
if ( $form['id'] == $this->_form_id ) {
$hash = $this->get_selected_field_ids_hash();
gform_add_meta( $entry['id'], "_gfrf_field_ids_{$hash}", $this->get_selected_field_ids() );
}
}
}
new GFRandomFields( 167, 2, array( 1, 2, 3, 4, 5 ) );
new GFRandomFields( 167, 2, array( 8, 9, 10 ) );
{"0":{"id":167,"title":"Random Fields","description":"We would love to hear from you! Please fill out this form and we will get in touch with you shortly.","labelPlacement":"top_label","maxEntriesMessage":"","button":{"type":"text","text":"Submit","imageUrl":""},"fields":[{"type":"text","adminLabel":"","allowsPrepopulate":false,"defaultValue":"","description":"","content":"","cssClass":"","errorMessage":"","id":1,"inputName":"","isRequired":true,"label":"Question #1","noDuplicates":"","size":"medium","postCustomFieldName":"","displayAllCategories":false,"displayCaption":"","displayDescription":"","displayTitle":"","inputType":"","rangeMin":"","rangeMax":"","calendarIconUrl":"","dateFormat":"","phoneFormat":"","defaultCountry":"","defaultProvince":"","defaultState":"","hideAddress2":"","hideCountry":"","hideState":"","inputs":null,"nameFormat":"","allowedExtensions":"","captchaType":"","page_number":"","captchaTheme":"","simpleCaptchaSize":"","simpleCaptchaFontColor":"","simpleCaptchaBackgroundColor":"","productField":"","enablePasswordInput":"","maxLength":"","enablePrice":"","basePrice":"","calculationFormula":"","calculationRounding":"","enableCalculation":"","disableQuantity":false,"inputMask":false,"inputMaskValue":"","formId":167,"descriptionPlacement":"below","visibility":"visible","displayOnly":"","labelPlacement":"","subLabelPlacement":"","placeholder":"","multipleFiles":false,"maxFiles":"","useRichTextEditor":false,"gp-unique-id_starting_number":"","choices":"","conditionalLogic":""},{"type":"text","adminLabel":"","allowsPrepopulate":false,"defaultValue":"","description":"","content":"","cssClass":"","errorMessage":"","id":2,"inputName":"","isRequired":true,"label":"Question #2","noDuplicates":"","size":"medium","postCustomFieldName":"","displayAllCategories":false,"displayCaption":"","displayDescription":"","displayTitle":"","inputType":"","rangeMin":"","rangeMax":"","calendarIconUrl":"","dateFormat":"","phoneFormat":"","defaultCountry":"","defaultProvince":"","defaultState":"","hideAddress2":"","hideCountry":"","hideState":"","inputs":null,"nameFormat":"","allowedExtensions":"","captchaType":"","page_number":"","captchaTheme":"","simpleCaptchaSize":"","simpleCaptchaFontColor":"","simpleCaptchaBackgroundColor":"","productField":"","enablePasswordInput":"","maxLength":"","enablePrice":"","basePrice":"","calculationFormula":"","calculationRounding":"","enableCalculation":"","disableQuantity":false,"inputMask":false,"inputMaskValue":"","formId":167,"descriptionPlacement":"below","visibility":"visible","displayOnly":"","choices":"","conditionalLogic":""},{"type":"text","adminLabel":"","allowsPrepopulate":false,"defaultValue":"","description":"","content":"","cssClass":"","errorMessage":"","id":3,"inputName":"","isRequired":true,"label":"Question #3","noDuplicates":"","size":"medium","postCustomFieldName":"","displayAllCategories":false,"displayCaption":"","displayDescription":"","displayTitle":"","inputType":"","rangeMin":"","rangeMax":"","calendarIconUrl":"","dateFormat":"","phoneFormat":"","defaultCountry":"","defaultProvince":"","defaultState":"","hideAddress2":"","hideCountry":"","hideState":"","inputs":null,"nameFormat":"","allowedExtensions":"","captchaType":"","page_number":"","captchaTheme":"","simpleCaptchaSize":"","simpleCaptchaFontColor":"","simpleCaptchaBackgroundColor":"","productField":"","enablePasswordInput":"","maxLength":"","enablePrice":"","basePrice":"","calculationFormula":"","calculationRounding":"","enableCalculation":"","disableQuantity":false,"inputMask":false,"inputMaskValue":"","formId":167,"descriptionPlacement":"below","visibility":"visible","displayOnly":"","labelPlacement":"","subLabelPlacement":"","placeholder":"","multipleFiles":false,"maxFiles":"","useRichTextEditor":false,"gp-unique-id_starting_number":"","choices":"","conditionalLogic":""},{"type":"text","adminLabel":"","allowsPrepopulate":false,"defaultValue":"","description":"","content":"","cssClass":"","errorMessage":"","id":4,"inputName":"","isRequired":true,"label":"Question #4","noDuplicates":"","size":"medium","postCustomFieldName":"","displayAllCategories":false,"displayCaption":"","displayDescription":"","displayTitle":"","inputType":"","rangeMin":"","rangeMax":"","calendarIconUrl":"","dateFormat":"","phoneFormat":"","defaultCountry":"","defaultProvince":"","defaultState":"","hideAddress2":"","hideCountry":"","hideState":"","inputs":null,"nameFormat":"","allowedExtensions":"","captchaType":"","page_number":"","captchaTheme":"","simpleCaptchaSize":"","simpleCaptchaFontColor":"","simpleCaptchaBackgroundColor":"","productField":"","enablePasswordInput":"","maxLength":"","enablePrice":"","basePrice":"","calculationFormula":"","calculationRounding":"","enableCalculation":"","disableQuantity":false,"inputMask":false,"inputMaskValue":"","formId":167,"descriptionPlacement":"below","visibility":"visible","displayOnly":"","choices":"","conditionalLogic":""},{"type":"text","adminLabel":"","allowsPrepopulate":false,"defaultValue":"","description":"","content":"","cssClass":"","errorMessage":"","id":5,"inputName":"","isRequired":true,"label":"Question #5","noDuplicates":"","size":"medium","postCustomFieldName":"","displayAllCategories":false,"displayCaption":"","displayDescription":"","displayTitle":"","inputType":"","rangeMin":"","rangeMax":"","calendarIconUrl":"","dateFormat":"","phoneFormat":"","defaultCountry":"","defaultProvince":"","defaultState":"","hideAddress2":"","hideCountry":"","hideState":"","inputs":null,"nameFormat":"","allowedExtensions":"","captchaType":"","page_number":"","captchaTheme":"","simpleCaptchaSize":"","simpleCaptchaFontColor":"","simpleCaptchaBackgroundColor":"","productField":"","enablePasswordInput":"","maxLength":"","enablePrice":"","basePrice":"","calculationFormula":"","calculationRounding":"","enableCalculation":"","disableQuantity":false,"inputMask":false,"inputMaskValue":"","formId":167,"descriptionPlacement":"below","visibility":"visible","displayOnly":"","choices":"","conditionalLogic":""},{"type":"select","adminLabel":"","allowsPrepopulate":false,"defaultValue":"","description":"","content":"","cssClass":"","errorMessage":"","id":6,"inputName":"","isRequired":false,"label":"Who are you?","noDuplicates":"","size":"medium","postCustomFieldName":"","displayAllCategories":false,"displayCaption":"","displayDescription":"","displayTitle":"","inputType":"","rangeMin":"","rangeMax":"","calendarIconUrl":"","dateFormat":"","phoneFormat":"","defaultCountry":"","defaultProvince":"","defaultState":"","hideAddress2":"","hideCountry":"","hideState":"","inputs":null,"nameFormat":"","allowedExtensions":"","captchaType":"","page_number":"","captchaTheme":"","simpleCaptchaSize":"","simpleCaptchaFontColor":"","simpleCaptchaBackgroundColor":"","productField":"","enablePasswordInput":"","maxLength":"","enablePrice":"","basePrice":"","choices":[{"text":"First Choice","value":"First Choice","isSelected":false,"price":""},{"text":"Second Choice","value":"Second Choice","isSelected":false,"price":""},{"text":"Third Choice","value":"Third Choice","isSelected":false,"price":""}],"calculationFormula":"","calculationRounding":"","enableCalculation":"","disableQuantity":false,"inputMask":false,"inputMaskValue":"","formId":167,"descriptionPlacement":"below","visibility":"visible","displayOnly":"","conditionalLogic":""},{"type":"page","id":7,"label":"","adminLabel":"","isRequired":false,"size":"medium","errorMessage":"","inputs":null,"displayOnly":true,"nextButton":{"type":"text","text":"Next","imageUrl":""},"previousButton":{"type":"text","text":"Previous","imageUrl":""},"formId":167,"description":"","allowsPrepopulate":false,"inputMask":false,"inputMaskValue":"","inputType":"","labelPlacement":"","descriptionPlacement":"","subLabelPlacement":"","placeholder":"","cssClass":"","inputName":"","visibility":"","noDuplicates":false,"defaultValue":"","choices":"","conditionalLogic":"","productField":""},{"type":"text","id":8,"label":"Alt Question #1","adminLabel":"","isRequired":false,"size":"medium","errorMessage":"","inputs":null,"formId":167,"description":"","allowsPrepopulate":false,"inputMask":false,"inputMaskValue":"","inputType":"","labelPlacement":"","descriptionPlacement":"","subLabelPlacement":"","placeholder":"","cssClass":"","inputName":"","visibility":"visible","noDuplicates":false,"defaultValue":"","choices":"","conditionalLogic":"","productField":"","enablePasswordInput":"","maxLength":"","multipleFiles":false,"maxFiles":"","calculationFormula":"","calculationRounding":"","enableCalculation":"","disableQuantity":false,"displayAllCategories":false,"useRichTextEditor":false,"gp-unique-id_starting_number":""},{"type":"text","id":9,"label":"Alt Question #2","adminLabel":"","isRequired":false,"size":"medium","errorMessage":"","inputs":null,"formId":167,"description":"","allowsPrepopulate":false,"inputMask":false,"inputMaskValue":"","inputType":"","labelPlacement":"","descriptionPlacement":"","subLabelPlacement":"","placeholder":"","cssClass":"","inputName":"","visibility":"visible","noDuplicates":false,"defaultValue":"","choices":"","conditionalLogic":"","productField":"","enablePasswordInput":"","maxLength":"","multipleFiles":false,"maxFiles":"","calculationFormula":"","calculationRounding":"","enableCalculation":"","disableQuantity":false,"displayAllCategories":false,"useRichTextEditor":false,"gp-unique-id_starting_number":""},{"type":"text","id":10,"label":"Alt Question #3","adminLabel":"","isRequired":false,"size":"medium","errorMessage":"","inputs":null,"formId":167,"description":"","allowsPrepopulate":false,"inputMask":false,"inputMaskValue":"","inputType":"","labelPlacement":"","descriptionPlacement":"","subLabelPlacement":"","placeholder":"","cssClass":"","inputName":"","visibility":"visible","noDuplicates":false,"defaultValue":"","choices":"","conditionalLogic":"","productField":"","enablePasswordInput":"","maxLength":"","multipleFiles":false,"maxFiles":"","calculationFormula":"","calculationRounding":"","enableCalculation":"","disableQuantity":false,"displayAllCategories":false,"useRichTextEditor":false,"gp-unique-id_starting_number":""}],"useCurrentUserAsAuthor":true,"descriptionPlacement":"below","cssClass":"","enableHoneypot":false,"enableAnimation":false,"postContentTemplateEnabled":false,"postTitleTemplateEnabled":false,"postTitleTemplate":"","postContentTemplate":"","lastPageButton":{"type":"text","text":"Previous","imageUrl":""},"pagination":{"type":"percentage","pages":[""],"style":"blue","backgroundColor":null,"color":null,"display_progressbar_on_confirmation":false,"progressbar_completion_text":null},"firstPageCssClass":"","limitEntries":false,"limitEntriesCount":"","limitEntriesMessage":"","limitEntriesPeriod":"","requireLogin":false,"requireLoginMessage":"","scheduleForm":false,"scheduleStart":"","scheduleStartHour":"","scheduleStartMinute":"","scheduleStartAmpm":"","scheduleEnd":"","scheduleEndHour":"","scheduleEndMinute":"","scheduleEndAmpm":"","scheduleMessage":"","confirmations":[{"type":"message","message":"Thanks for contacting us! We will get in touch with you shortly.","url":"","pageId":"","queryString":"","disableAutoformat":false,"id":"5179a76e802a2","name":"Default Confirmation","isDefault":true}],"notifications":[{"to":"{admin_email}","subject":"New submission from {form_title}","message":"{all_fields}","toType":"email","event":"form_submission","name":"Admin Notification","type":"admin","id":"5179a76e80754"}]},"version":"2.2.2"}
@spivurno
Copy link
Author

spivurno commented Nov 26, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment