spivurno
4/13/2014 - 12:51 PM

Gravity Perks // GP Nested Forms // Get Sum of Nested Form Field Column

Gravity Perks // GP Nested Forms // Get Sum of Nested Form Field Column

<?php
/**
* Gravity Wiz // Gravity Perks // Get Sum of Nested Form Fields
*
* Get the sum of a column from a Gravity Forms List field.
*
* @version   1.5
* @author    David Smith <david@gravitywiz.com>
* @license   GPL-2.0+
* @link      http://gravitywiz.com/...
* @copyright 2014 Gravity Wiz
*/
class GPNF_Field_Sum {

    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 GPNFFieldSum( ' . json_encode( $args ) . ' );';
        $slug = "gpnf_column_sum_{$this->_args['form_id']}_{$this->_args['target_field_id']}";

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

    }

    public function maybe_output_script( $form ) {

    	if( ! has_action( 'wp_footer', array( $this, 'script' ) ) ) {
    		add_action( 'wp_footer', array( $this, 'script' ) );
    		add_action( 'gform_preview_footer', array( $this, 'script' ) );
	    }

        return $form;
    }

    public function script() {
        ?>

        <script type="text/javascript">

            var GPNFFieldSum;

            ( function( $ ){

                GPNFFieldSum = 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 ) {
                            console.log( 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 = gformToNumber( entries[i][fieldId] ? entries[i][fieldId] : 0 );

                            console.log( 'count', count, entries[i][fieldId] );

                            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' => 5,
    'target_field_id' => 7
) );