Recalculate Field Value on View

🧪

Experimental Snippet

This snippet was discovered in the wizard’s chaotic laboratory — an unpolished experiment, conjured to solve a niche challenge. Use at your own risk.

Recalculate a calculated field’s value every time it’s viewed.

Works great with Date Time Calculator’s :age modifier.

Instructions

See “Where do I put snippets?” in our documentation for installation instructions.

Code

Filename: gpdtc-recalc.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
/**
 * Gravity Perks // Date Time Calculator // Recalculate Field Value on View
 * https://gravitywiz.com/documentation/gravity-forms-date-time-calculator/
 *
 * Experimental Snippet 🧪
 *
 * Recalculate a calculated field's value every time it's viewed.
 *
 * Works great with Date Time Calculator's [:age modifier][1].
 *
 * [1]: https://gravitywiz.com/documentation/gravity-forms-date-time-calculator/#calculating-age
 */
add_action( 'wp_loaded', function() {

	$form_id  = 123;  // Change this to the form's ID
	$field_id = 4;    // Change this to the Calculation field's ID.

	$values      = array();
	$calculating = false; // Flag to prevent infinite recursion

	add_filter( sprintf( 'gform_get_input_value_%s', $form_id ), function( $value, $entry, $field, $input_id ) use ( $field_id, &$values, &$calculating ) {
		// Prevent infinite recursion
		if ( $calculating ) {
			return $value;
		}

		if ( $field['id'] !== $field_id ) {
			$values[ $field['id'] ] = $value;
			return $value;
		}

		// Set flag to prevent recursion
		$calculating = true;

		$form   = GFAPI::get_form( $entry['form_id'] );
		$_entry = $entry + $values;
		$calculated_value = GFCommon::calculate( $field, $form, $_entry );

		GFAPI::update_entry_field( $_entry['id'], $field_id, $calculated_value );
		// Reset flag
		$calculating = false;

		return $calculated_value;
	}, 10, 4 );

	// GravityView Support.
	add_filter( 'gravityview/field/number/value', function( $value, $field, $view, $form, $entry ) use ( $field_id, $form_id ) {
		if ( $field->ID != $field_id && $form->ID != $form_id ) {
			return $value;
		}
		$orig_entry = GFAPI::get_entry( $entry->ID );
		return rgar( $orig_entry, $field_id );
	}, 10, 5 );

} );

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.