Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
add_filter( 'gform_calculation_formula', 'sum_list_column', 10, 4 );
function sum_list_column( $formula, $field, $form, $lead ) {
// {List:1.3} - {Label:ID.Column}
preg_match_all( '/{[^{]*?:(\d+?).(\d+?)}/mi', $formula, $matches, PREG_SET_ORDER );
if( is_array( $matches ) ) {
foreach( $matches as $match ) {
foreach( $form['fields'] as $field ) {
if( $field['type'] != 'list' && $field['id'] != $match[1] )
continue;
$list_values = unserialize( $lead[$match[1]] );
$column = $field['choices'][$match[2]-1]['text'];
$sum = 0;
foreach( $list_values as $value ) {
$sum += GFCommon::to_number( $value[$column] );
}
$formula = str_replace( $match[0], $sum, $formula );
}
}
}
return $formula;
}
@osqueza

This comment has been minimized.

Copy link

osqueza commented Feb 13, 2015

Hey this is a great snippet, Im trying to do something similar to this here: http://velting.com/test-form/
What I need is to multiply column number 2 with number 3. How can I change your code so this can be done?

Thanks in advance!

@tareqhi

This comment has been minimized.

Copy link

tareqhi commented Mar 30, 2015

hey osqueza, I tried it on my form. do this-
at first you noticed that to show the calculation result you must use number field. in calculation of the number field, you can add this {List:1.2} * {List:1.3) or whatever to column number 2 with number 3

@flinhardt

This comment has been minimized.

Copy link

flinhardt commented Apr 19, 2015

Sorry, I do not know how to use it. Can you please tell me what values I have to change in order to make this work? Thanks!

@jonmac1234

This comment has been minimized.

Copy link

jonmac1234 commented Jul 13, 2015

Hi richardW8k,

Thanks for this. Is there any way to modify so that the sum appears in real-time, as users enter data in list fields? I know that the 'gform_calculation_formula' filter only works when a user submits, but is there any other way to get the same result, except in real-time?

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.