Skip to content

Instantly share code, notes, and snippets.

@richardW8k
Last active April 18, 2018 15:03
Show Gist options
  • 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;
}
@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