tannerm
1/23/2015 - 10:04 PM

Call GravityForms custom price function before coupons while maintaining coupon functionality.

Call GravityForms custom price function before coupons while maintaining coupon functionality.

/**
 * Custom price the Registration form and support other custom price functions
 * Yes this is kind of a hack, but we need out function to fire first
 */
var registrationTotal = function() {
	var SELF = this;

	SELF.init = function() {
		// This would be the right way to make this happen if the coupons extension didn't mess it up
		// gform.addFilter('gform_product_total', SELF.swapVars);
		$(window).load(SELF.setgFormTotal);
	};

	/**
	 * Swap filter variables to match expected function variables
	 * @param total
	 * @param formId
	 * @returns {*}
	 */
	SELF.swapVars = function(total, formId) {
		return SELF.regTotal(formId, total);
	};

	/**
	 * Redefine gform_product_total to call our functionality first
	 */
	SELF.setgFormTotal = function(){
		window.gform_product_total = function(formId, total){
			total = SELF.regTotal(formId, total);

			// only call the old function if there was one
			if (SELF["oldgFormTotal"]) {
				total = SELF.oldgFormTotal(formId, total);
			}

			return total;
		}
	};

	/**
	 * Custom calculations for member registration
	 *
	 * @param formId
	 * @param total
	 * @returns {*}
	 */
	SELF.regTotal = function (formId, total) {
		//only apply logic to membership form
		if (formId != 1) {
			return total;
		}

		var productID     = '16';
		var product       = $(document.getElementById('input_' + formId + '_' + productID)).find('input:checked').val();
		var freeDivisions = numFreeDivisions(product);
		var divisionPrice = 175;

		// Do not charge for free Divisions (if applicable)
		if ( freeDivisions ) {
			var $divisions = $(document.getElementById('field_' + formId + '_19')).find("input:checked, select");

			// subtract *up to* the total number of free Divisions from the price
			if ($divisions.length > freeDivisions) {
				total -= (freeDivisions * divisionPrice);
			} else {
				total -= ( $divisions.length * divisionPrice);
			}
		}

		// Calculate automatic renewal discount
		if ($(document.getElementById('input_' + formId + '_31')).find('input').attr('checked')) {
			total -= total * .1;
		}

		return total;
	};

	// store previous gform_product_total
	SELF.oldgFormTotal = window["gform_product_total"];

};

new registrationTotal().init();