Gravity Wiz // Gravity Forms User Registration // One Way Mapping
<?php
/**
* Gravity Wiz // Gravity Forms User Registration // One Way Mapping
*
* By default, fields mapped to a user meta key on an User Registration Update Feed will be populated with the current
* user meta value. This snippet allows you to specify form fields that should update the user meta but not be populated
* with the existing value when the form is rendered.
*
* @version 1.0
* @author David Smith <david@gravitywiz.com>
* @license GPL-2.0+
* @link http://gravitywiz.com/...
*/
class GW_GFUR_One_Way_Mapping {
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(
'feed_id' => false,
'keys' => array()
) );
if( ! is_array( $this->_args['keys'] ) ) {
$this->_args['keys'] = array( $this->_args['keys'] );
}
// 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' ) );
}
public 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;
}
// carry on
remove_filter( 'gform_pre_render', array( 'GFUser', 'maybe_prepopulate_form' ) );
add_filter( 'gform_pre_render', array( $this, 'maybe_prepopulate_form' ) );
}
public function maybe_prepopulate_form( $form ) {
$feed = GFUserData::get_update_feed( $form['id'] );
// if no feed, return form unmodified
if( ! $feed ) {
return $form;
} else
// if the user is not logged in, add action to hide form and display error message
if( ! is_user_logged_in() ) {
add_action( 'gform_get_form_filter_' . $form['id'], array( 'GFUser', 'hide_form' ) );
return $form;
} else {
if( $feed['id'] == $this->_args['feed_id'] || ! $this->_args['feed_id'] ) {
$feed = $this->remove_meta_keys( $feed, $this->_args['keys'] );
}
$form = GFUser::prepopulate_form( $form, $feed );
}
return $form;
}
public function remove_meta_keys( $feed, $keys ) {
$cleaned_meta = array();
foreach( $feed['meta'] as $key => $value ) {
if( ! in_array( $key, $keys ) ) {
$cleaned_meta[ $key ] = $value;
}
}
$cleaned_meta['user_meta'] = array();
foreach( $feed['meta']['user_meta'] as $meta ) {
if( ! in_array( $meta['meta_name'], $keys ) ) {
$cleaned_meta['user_meta'][][ $meta['meta_name'] ] = $meta['meta_value'];
}
}
$feed['meta'] = $cleaned_meta;
return $feed;
}
}
# Configuration
new GW_GFUR_One_Way_Mapping( array(
'feed_id' => 45,
'keys' => 'paperless_billing'
) );