spivurno
5/2/2014 - 9:39 PM

Gravity Wiz // Gravity Forms // Subtotal Merge Tag // Support Modified Subtotals

Gravity Wiz // Gravity Forms // Subtotal Merge Tag // Support Modified Subtotals

<?php
/**
* On the front-end, GF Calculations will include other calculation fields in the calculation formula, even if that
* calculation field comes after the field being currently calculated. On the back-end, calculation fields in formulas
* for other calculation fields that preceed them, are not contributed towards that calculated total.
* 
* This means if you are using the {subtotal} merge tag (http://gravitywiz.com/subtotal-merge-tag-for-calculations/) to
* show the Subtotal and then using the {subtotal} merge tag in a field after that subtotal field to add tax, you would
* need to modify the Subtotal field to subtract the tax field amount.
* 
* Subtotal: {subtotal} / 1.1
* Tax:		{subtotal} * 0.1
* 
* Without this snippet, the backend would also reduce the Subtotal according the modified formula; however, since the 
* Tax field comes after the subtotal field and GF does not support using calculation fields in formulas for fields that 
* preceed them, the Tax is not added to the calculated value for the Subtotal field and you would get a lower value than 
* expected.
* 
* This snippet simply replaces the modified formula with just the {subtotal} merge tag to account for the different
* behaviors between GF front-end and back-end handling of Calculation fields.
* 
* With love, from GravityWiz.com
* 
*/

add_filter( 'gform_pre_validation', 'modify_subtotal_calculation', 9 );
function modify_subtotal_calculation( $form ) {

	// update "295" to the ID of your form
	if( $form['id'] != 295 )
		return $form;
	
	foreach( $form['fields'] as &$field ) {
		// update "11" to the ID of your subtotal field
		if( $field['id'] == 11 )
			$field['calculationFormula'] = '{subtotal}';
	}
	
	return $form;
}