spivurno
5/5/2017 - 8:31 PM

Gravity Wiz // Gravity Forms // Rotating Values

Gravity Wiz // Gravity Forms // Rotating Values

<?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-round-robin.php
 */
/**
 * Gravity Wiz // Gravity Forms // Rotating Values
 * http://gravitywiz.com/
 */
add_filter( 'gform_entry_post_save', function( $entry ) {

	// Specify an array of values that will be rotated through.
	$rotation = array( 'Tom', 'Richard', 'Harry' );

	// Specify the form ID for which this functioanlity applies.
	$form_id = 1722;

	// Specify the field ID in which the current rotation value will be saved.
	$field_id = 1;

	/* DON'T EDIT BELOW THIS LINE */

	// Bail out of this is not our designated form.
	if( $entry['form_id'] != $form_id ) {
		return $entry;
	}

	// Get the last submitted entry.
	$last_entry = rgar( GFAPI::get_entries( $entry['form_id'], array( 'status' => 'active' ), array( 'direction' => 'desc' ), array( 'offset' => 1, 'page_size' => 1 ) ), 0 );

	// Get the value submitted for our designated field in the last entry.
	$last_value = rgar( $last_entry, $field_id );

	// Determine the next index at which to fetch our value.
	$next_index = empty( $last_value ) ? 0 : array_search( $last_value, $rotation ) + 1;
	if( $next_index > count( $rotation ) - 1 ) {
		$next_index = 0;
	}

	// Get the next value based on our rotation.
	$next_value = $rotation[ $next_index ];

	// Update the value of our designated field in the database.
	GFAPI::update_entry_field( $entry['id'], $field_id, $next_value );

	// Update the value of our designated field in the $entry object that will be used to continuing processing the current submission.
	$entry[ $field_id ] = $next_value;

	return $entry;
}, 7 );