spivurno
5/1/2014 - 2:02 AM

Gravity Wiz // Gravity Forms // Product Count

Gravity Wiz // Gravity Forms // Product Count

<?php
/**
* Gravity Wiz // Gravity Forms // Product Count
*
* Get the total number of products selected. Particularly useful in combination with the GP Conditional Pricing
* perk to create pricing rules based on product count.
*
* @version	 1.0
* @author    David Smith <david@gravitywiz.com>
* @license   GPL-2.0+
* @link      http://gravitywiz.com/...
* @copyright 2014 Gravity Wiz
*/
class GW_Product_Count {

    private static $script_output;

    function __construct( $args ) {

        $this->_args = wp_parse_args( $args, array(
            'form_id'        => false,
            'count_field_id' => false,
            'products'       => false
        ) );

        // support providing 'products' as single integer or array of integers
        if( $this->_args['products'] && ! is_array( $this->_args['products'] ) )
            $this->_args['products'] = array( $this->_args['products'] );

        add_filter( 'gform_pre_render',            array( $this, 'maybe_output_script' ) );
        add_action( 'gform_register_init_scripts', array( $this, 'add_init_script' ) );
        add_action( 'gform_pre_validation',        array( $this, 'override_submitted_value') );

    }

    function maybe_output_script( $form ) {

        if( $this->is_applicable_form( $form['id'] ) && ! self::$script_output )
            $this->output_script();

        return $form;
    }

    function output_script() {
        ?>

        <script type="text/javascript">

            ( function( $ ) {

                window.GWProductCount = 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() {

                        console.log( 'init' );

                        gform.addFilter( 'gform_product_total', function( price, formId ) {
                            self.updateProductCount( formId, self.products, self.countFieldId );
                            return price;
                        } )

                    }

                    self.updateProductCount = function( formId, productIds, countFieldId ) {

                        var count    = 0,
                            quantity = 0;

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

                            var qty   = gformGetProductQuantity( formId, productIds[i] ),
                                price = gformCalculateProductPrice( formId, productIds[i] );

                            // temp hack: if no price, assume no product is selected, otherwise a quantity of "1" will be returned for radio button products
                            // even though no product is selected
                            if( ! price )
                                continue;

                            quantity += qty;

                            if( qty > 0 )
                                count += 1;

                        }

                        $( '#input_' + formId + '_' + countFieldId ).val( count );

                    }

                    self.init();

                }

            } )( jQuery );

        </script>

        <?php
        self::$script_output = true;
    }

    function add_init_script( $form ) {

        if( ! $this->is_applicable_form( $form['id'] ) )
            return;

        $products = $this->_args['products'];
        if( ! $products ) {
            $product_fields = GFCommon::get_product_fields_by_type( $form, array( 'product' ), false );
            $products = wp_list_pluck( $product_fields, 'id' );
        }

        $args = array(
            'formId'       => $this->_args['form_id'],
            'countFieldId' => $this->_args['count_field_id'],
            'products'     => $products
        );

        $script = 'new GWProductCount( ' . json_encode( $args ) . ' );';
        $slug = implode( '_', array( 'gw_product_count', $this->_args['form_id'], $this->_args['count_field_id'] ) );

        GFFormDisplay::add_init_script( $this->_args['form_id'], $slug, GFFormDisplay::ON_PAGE_RENDER, $script );

        return;
    }

    function override_submitted_value( $form ) {



        //$_POST["input_{$this->count_field_id}"] = $day_count;
        return $form;
    }

    function is_applicable_form( $form_id ) {
        return $this->_args['form_id'] == $form_id;
    }

}

new GW_Product_Count( array(
    'form_id'        => 503,
    'count_field_id' => 198,
    'products'       => array( 162, 163 )
) );