spivurno of Gravity Wiz
4/29/2014 - 2:56 PM

Gravity Wiz // Gravity Perks // Get Sum of Nested Form Field Column

Gravity Wiz // Gravity Perks // Get Sum of Nested Form Field Column

<?php
/**
* Gravity Wiz // Gravity Perks // Get Sum of Nested Form Field Column
* 
* Get the sum of a field ID from all "child" entries of a Nested Form.
* 
* @version	 1.0
* @author    David Smith <david@gravitywiz.com>
* @license   GPL-2.0+
* @link      http://gravitywiz.com/...
* @copyright 2014 Gravity Wiz
*/
class GPNF_Field_Sum {

    private static $script_output = false;

    public function __construct( $args = array() ) {
        
        // make sure we're running the required minimum version of Gravity Forms
        if( ! property_exists( 'GFCommon', 'version' ) || ! version_compare( GFCommon::$version, '1.8', '>=' ) )
            return;
        
        // set our default arguments, parse against the provided arguments, and store for use throughout the class
        $this->_args = wp_parse_args( $args, array( 
            'form_id' => false,
            'nested_form_field_id' => false,
            'nested_field_id' => false,
            'target_field_id' => false
        ) );

        extract( $this->_args );

        // time for hooks
        add_action( "gform_register_init_scripts_{$form_id}", array( $this, 'register_init_script' ) );
        add_action( "gform_pre_render_{$form_id}", array( $this, 'maybe_output_script' ) );
        
    }

    public function register_init_script( $form ) {

        $args = array(
            'formId' => $this->_args['form_id'],
            'nestedFormFieldId' => $this->_args['nested_form_field_id'],
            'nestedFieldId' => $this->_args['nested_field_id'],
            'targetFieldId' => $this->_args['target_field_id']
        );

        $script = 'new GPNFColumnSum( ' . json_encode( $args ) . ' );';
        $slug = "gpnf_column_sum_{$this->_args['form_id']}_{$this->_args['targetFieldId']}";

        GFFormDisplay::add_init_script( $form['id'], $slug, GFFormDisplay::ON_PAGE_RENDER, $script );

    }

    public function maybe_output_script( $form ) {

        if( ! self::$script_output )
            $this->script();

        return $form;
    }

    public function script() {
        ?>

        <script type="text/javascript">

            var GPNFColumnSum;

            ( function( $ ){

                GPNFColumnSum = function( args ) {

                    var self = this;

                    // copy all args to current object: formId, fieldId
                    for( prop in args ) {
                        if( args.hasOwnProperty( prop ) )
                            self[prop] = args[prop];
                    }

                    self.init = function() {

                        var gpnf = $( '#gform_wrapper_' + self.formId ).data( 'GPNestedForms_' + self.nestedFormFieldId );

                        gpnf.viewModel.entries.subscribe( function( newValue ) {
                            self.updateSum( newValue, self.nestedFieldId, self.targetFieldId, self.formId )
                        } );

                        self.updateSum( gpnf.viewModel.entries(), self.nestedFieldId, self.targetFieldId, self.formId );

                    }

                    self.calculateSum = function( entries, fieldId ) {

                        var total = 0;

                        for( var i = 0; i < entries.length; i++ ) {

                            var count = entries[i][fieldId] ? entries[i][fieldId] : 0;

                            if( ! isNaN( parseFloat( count ) ) )
                                total += parseFloat( count );

                        }

                        return total;
                    }

                    self.updateSum = function( entries, nestedFieldId, targetFieldId, formId ) {

                        var total = self.calculateSum( entries, nestedFieldId );

                        $( '#input_' + formId + '_' + targetFieldId ).val( total ).change();

                    }

                    self.init();

                }

            } )( jQuery );

        </script>

        <?php
    }

}

# Configuration

new GPNF_Field_Sum( array(
    'form_id' => 469,
    'nested_form_field_id' => 2,
    'nested_field_id' => 3,
    'target_field_id' => 4
) );