spivurno
7/3/2014 - 12:36 PM

Gravity Wiz // Gravity Forms // Populate Field With User Meta

Gravity Wiz // Gravity Forms // Populate Field With User Meta

<?php
/**
 * ============================================================================================
 * STOP! There's a better way.
 * 
 * The functionality provided by this snippet is available via Gravity Forms Populate Anything. 
 * 
 * Don't get your hands dirty mucking about with code. Populate Anything provides a seamlessly
 * integrated interface for filtering exactly which users are populated and what data from 
 * those users is displayed.
 * 
 * https://gravitywiz.com/documentation/gravity-forms-populate-anything/
 * ============================================================================================
 *  
 * Gravity Wiz // Gravity Forms // Populate Field With User Meta
 *
 * Populate choice-based fields (i.e. drop downs, radios, checkboxes) with data from WordPress users.
 *
 * @version	  1.0
 * @author    David Smith <david@gravitywiz.com>
 * @license   GPL-2.0+
 * @link      http://gravitywiz.com/...
 *
 * @todo
 *  + combine with GW Populate Users snippet
 *  + add support for single user / single meta key / single + multiple values
 *  + add support for single user / multiple meta keys
 *  + add support for multiple users / single meta key / single + multiple values
 *  + add support for multiple users / multiple meta keys
 */
class GW_Populate_User_Meta {

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

        // make sure we're running the required minimum version of Gravity Forms
        if( ! property_exists( 'GFCommon', 'version' ) )
            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,
            'field_id'             => false,
            'meta_keys'            => array(),
            'show_empty_values'    => false,
            'value_template'       => false,
            'label_template'       => false
        ) );

        if( ! is_array( $this->_args['meta_keys'] ) )
            $this->_args['meta_keys'] = ! $this->_args['meta_keys'] ? array() : array( $this->_args['meta_keys'] );

        // time for hooks
        add_action( "gform_pre_render_{$this->_args['form_id']}",            array( $this, 'populate' ) );
        add_action( "gform_pre_submission_filter_{$this->_args['form_id']}", array( $this, 'populate' ) );

    }

    public function populate( $form ) {

        foreach( $form['fields'] as &$field ) {

            if( $field['id'] != $this->_args['field_id'] )
                continue;

            $user = wp_get_current_user();
            $choices = array();

            // if first choice has text but no value, assume it is a placeholder and preserve
            if( rgars( $field, 'choices/0/text' ) && ! rgars( $field, 'choices/0/value' ) )
                $choices[] = $field['choices'][0];

            foreach( $this->_args['meta_keys'] as $meta_key ) {

                $value = $this->get_user_value( $user, $meta_key, $this->_args['value_template'] );
                $label = $this->_args['value_template'] != $this->_args['label_template'] ? $this->get_user_value( $user, $meta_key, $this->_args['label_template'] ) : $value;

                if( ! $value && ! $this->_args['show_empty_values'] )
                    continue;

                $choices[] = array(
                    'text' => $label,
                    'value' => $value
                );

            }

            if( empty( $choices ) ) {
                $choices[] = array(
                    'text' => __( 'There are no options currently available.' ),
                    'value' => ''
                );
            }

            $field['choices'] = $choices;

            if( GFFormsModel::get_input_type( $field ) != 'checkbox' )
                continue;

            $field['inputs'] = array();

            foreach( $choices as $id => $choice ) {
                $field['inputs'][] = array(
                    'id' => sprintf( '%d.%d', $field['id'], $id + 1 ),
                    'label' => $choice['text'],
                    'name' => ''
                );
            }

        }

        return $form;
    }

    public function get_user_value( $user, $property, $template ) {

        if( ! $template ) {

            $template = $user->get( $property );

        } else {

            preg_match_all( '/{(.+?)}/', $template, $matches, PREG_SET_ORDER );
            foreach( $matches as $match ) {

                list( $tag, $prop ) = $match;

                $value = '';

                switch( $prop ) {
                    case 'meta_key':
                        $value = $property;
                        break;
                    case 'meta_value':
                        $value = $user->get( $property );
                        break;
                    default:
                        $value = $user->get( $prop );
                }

                $template = str_replace( $tag, $value, $template );

            }

        }

        return $template;
    }

    public function is_default_orderby( $orderby ) {
        $default_orderby = array( 'ID', 'login', 'nicename', 'email', 'url', 'registered', 'display_name', 'post_count', 'meta_value' );
        return in_array( $orderby, $default_orderby );
    }

}

# Configuration

new GW_Populate_User_Meta( array(
    'form_id'           => 540,
    'field_id'          => 1,
    'meta_keys'         => array( 'wpc_cf_acct_1', 'wpc_cf_acct_2', 'testing' )
) );