Skip to content

Instantly share code, notes, and snippets.

@richardW8k
Last active April 18, 2018 15:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richardW8k/8717834 to your computer and use it in GitHub Desktop.
Save richardW8k/8717834 to your computer and use it in GitHub Desktop.
<?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
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
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

@florianlinhardt
Copy link

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
Copy link

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