spivurno
3/3/2015 - 12:58 PM

Ounce // Gravity Forms // Date Rounder

Ounce // Gravity Forms // Date Rounder

<?php
/**
 * Ounce // Gravity Forms // Date Rounder
 *
 * Allows the ability to round the date up (or down) to a day of the month.
 *
 * @version	  1.0
 * @author    David Smith <david@gravitywiz.com>
 * @license   GPL-2.0+
 * @link      http://gravitywiz.com/...
 */
class CH_Date_Rounder {

    protected static $is_script_output = false;

    public function __construct( $args = array() ) {

        // 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,
	        'target_field_id' => false,
	        'source_field_id' => false
        ) );

        // do version check in the init to make sure if GF is going to be loaded, it is already loaded
        add_action( 'init', array( $this, 'init' ) );

    }

    function init() {

        // make sure we're running the required minimum version of Gravity Forms
        if( ! property_exists( 'GFCommon', 'version' ) || ! version_compare( GFCommon::$version, '1.8', '>=' ) ) {
            return;
        }

        // time for hooks
        add_filter( 'gform_pre_render', array( $this, 'load_form_script' ) );
        add_filter( 'gform_register_init_scripts', array( $this, 'add_init_script' ) );
	    add_filter( 'gform_enqueue_scripts', array( $this, 'enqueue_form_scripts' ) );

    }

	function enqueue_form_scripts( $form ) {

		if( $this->is_applicable_form( $form ) ) {
			wp_enqueue_script( 'moment', 'https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js' );
			add_filter( 'gform_noconflict_scripts', function( $scripts ) {
				$scripts[] = 'moment';
				return $scripts;
			} );
		}

		return $form;
	}

    function load_form_script( $form ) {

        if( $this->is_applicable_form( $form ) && ! self::$is_script_output ) {
            $this->output_script();
        }

        return $form;
    }

    function output_script() {
        ?>

        <script type="text/javascript">

            ( function( $ ) {

                window.CHDateRounder = function( args ) {

                    var self = this;

                    // copy all args to current object: (list expected props)
                    for( prop in args ) {
                        if( args.hasOwnProperty( prop ) )
                            self[prop] = args[prop];
                    }

                    self.init = function() {

                        self.$source = $( '#input_' + self.formId + '_' + self.sourceFieldId );
                        self.$target = $( '#input_' + self.formId + '_' + self.targetFieldId );

	                    self.$source.change( function() {
							self.populateRoundedDate( $( this ).val() );
	                    } );

	                    self.populateRoundedDate( self.$source.val() );

                    };

		                self.populateRoundedDate = function( date ) {

			                var dateBits = date.split( '/' ),
				                date     = moment( new Date( dateBits[2], dateBits[1] - 1, dateBits[0], 0, 0, 0, 0 ) ),
				                newDate  = false;

			                if( date.date() > 15 ) {
								newDate = date.add( 1, 'month' ).date( 1 );
			                } else {
				                newDate = date.date( 15 );
			                }

			                self.$target.val( newDate.format( 'DD/MM/YYYY' ) );

		                };

                    self.init();

                }

            } )( jQuery );

        </script>

        <?php

        self::$is_script_output = true;

    }

    function add_init_script( $form ) {

        if( ! $this->is_applicable_form( $form ) ) {
            return;
        }

        $args = array(
            'formId'        => $this->_args['form_id'],
            'sourceFieldId' => $this->_args['source_field_id'],
            'targetFieldId' => $this->_args['target_field_id']
        );

        $script = 'new CHDateRounder( ' . json_encode( $args ) . ' );';
        $slug   = implode( '_', array( 'ch_date_rounder', $this->_args['form_id'], $this->_args['source_field_id'], $this->_args['target_field_id'] ) );

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

    }

    function is_applicable_form( $form ) {

        $form_id = isset( $form['id'] ) ? $form['id'] : $form;

        return $form_id == $this->_args['form_id'];
    }

}

# Configuration

new CH_Date_Rounder( array(
	'form_id'         => 757,
	'target_field_id' => 50,
	'source_field_id' => 42
) );