gform_calculation_result

Description

This filter can be used to modify the result of a number field calculation or calculated product field.

Usage

The gform_calculation_result filter has both a JavaScript version and a PHP version. Both versions should be used.

The JavaScript version only overrides the calculation result on the front-end.

gform.addFilter( 'gform_calculation_result', function( result, formulaField, formId, calcObj ) {
    // do stuff

    return result;
} );

The PHP version overrides the calculation result when the calculation is rerun during submission using the field values saved in the entry.

add_filter( 'gform_calculation_result', function( $result, $formula, $field, $form, $entry ) {
    // do stuff

    return $result;
}, 10, 5 );

JavaScript Version

Parameters

  • result float

    The calculation result.

  • formulaField Javascript Object

    The current calculation field object. e.g.

    {"field_id":3,"formula":"{:1}+{:2}","rounding":""}

  • formId integer

    The ID of the form in use.

  • calcObj Javascript Object

    The calculation object.

Example

This example shows how you can perform a calculation using exponents.

gform.addFilter('gform_calculation_result', function( result, formulaField, formId, calcObj ) {
    if ( formId == '10' && formulaField.field_id == '3' ) {
        var exponent = calcObj.replaceFieldTags( formId, '{:2}', formulaField ),
            num = calcObj.replaceFieldTags( formId, '{:1}', formulaField );
        result = Math.pow( num, exponent );
    }
    return result;
} );

Placement

Your code snippet can be placed in a HTML field on your form or in a theme custom JavaScript file.

Source Code

This filter is located in js/gravityforms.js

PHP Version

Parameters

  • $result float

    The calculation result.

  • $formula string

    The formula after merge tags have been processed.

  • $field Field Object

    The calculation field currently being processed.

  • $form Form Object

    The form currently being processed.

  • $entry Entry Object

    The entry currently being processed.

Example

This example shows how you can perform a calculation using exponents.

add_filter( 'gform_calculation_result', function ( $result, $formula, $field, $form, $entry ) {
    if ( $form['id'] == 10 && $field['id'] == 3 ) {
        $exponent = (float) rgar( $entry, '2' );
        $num      = (float) rgar( $entry, '1' );
        $result   = pow( $num, $exponent );
    }

    return $result;
}, 10, 5 );

Placement

Your code snippet should be placed in the functions.php file of your active theme.

Source Code

This filter is located in GFCommon::calculate() in common.php