In this guide, we will share JavaScript code to calculate the Repeat Group number field sum. This will work during Repeat Group Pre-Fill, new repeat group creation and updating existing repeat group entries.
Please update the 3 fields based on your form template. The JavaScript field must be placed outside of the Repeat Group.
// Set number field to use for summary
var number_field_id = 'de63-1347-d4a3';
// Set summary number field
var sum_field_id = '479f-9e40-7187';
// Set repeat group of number field
var repeat_group_id = 'd042-be15-c265';
// Update sum field with all number fields in repeat entries
function update_sum_field( options ) {
// Set sum field total value
var sum_field_value = 0;
// Loop over repeat group entries
_.each( options.repeat_value, function( repeat_entry ) {
// Loop over repeat entry fields
_.each( repeat_entry, function( entry_field ) {
// Check field id for select options
if ( entry_field.component_id == number_field_id ) {
// Update sum field value
sum_field_value = sum_field_value + Number( entry_field.value );
}
} );
} );
// Update sum field with value
formyoula.form_fields[ sum_field_id ].set( { value: sum_field_value } );
}
// Listening to all field changes in an existing repeat group item
formyoula.form_entry.on( 'form:field:onRender', function( data ) {
// Check if this is repeat group
if ( data.view.model.get( 'component_id' ) != repeat_group_id ) return;
// Get all repeat entries and update sum field
update_sum_field( {
repeat_value: data.view.model.get( 'repeat_value' )
} );
} );
// Listening to all field changes in an existing repeat group item
formyoula.form_fields[ repeat_group_id ].on( 'repeat:item:change', function( data ) {
// Check if field updates are available
if ( !data || _.isEmpty( data.updated_sub_component ) ) return;
// Get the actual field that was changed
var component = data.updated_sub_component;
// Check if repeat field component changes should be tracked
if ( component.get( 'component_id' ) == number_field_id ) {
// Get all repeat entries and update sum field
update_sum_field( {
repeat_value: formyoula.form_fields[ repeat_group_id ].get( 'repeat_value' )
} );
}
} );
Import example form template.
[Example Form] Repeat Group Number Field Calculation (1).json4.5KB
For any questions, please contact us - [email protected] or the Formyoula in-app chat 🙂