Skip to content

Instantly share code, notes, and snippets.

@spivurno
Last active October 20, 2021 10:18
Show Gist options
  • Save spivurno/9707874 to your computer and use it in GitHub Desktop.
Save spivurno/9707874 to your computer and use it in GitHub Desktop.
Gravity Wiz // Gravity Forms Populate With Entries
<?php
/**
* Gravity Wiz // Gravity Forms Populate With Entries
*
* Populate choice-based fields (i.e. drop downs, radios, checkboxes) with data from Gravity Form entries.
*
* @version 1.0
* @author David Smith <[email protected]>
* @license GPL-2.0+
* @link http://gravitywiz.com/...
* @copyright 2013 Gravity Wiz
*/
class GW_Populate_Entries {
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(
'target_form_id' => false,
'target_field_id' => false, // must be a choice-based field (drop down, radio, checkbox)
'source_form_id' => false,
'value' => false, // can be a field ID or a 'template' string with merge tag support
'label' => false, // can be a field ID or a 'template' string with merge tag support
'query_args' => array()
) );
$this->_args['query_args'] = wp_parse_args( $this->_args['query_args'], array(
'status' => 'active',
'order' => 'asc',
'order_by' => 'date_created',
'nopaging' => true,
'offset' => 0,
'page_size' => 20,
'field_id' => false,
'field_value' => '',
'field_filters' => array()
) );
if( $this->_args['query_args']['field_id'] ) {
$this->_args['query_args']['field_filters'] = array(
array(
'key' => $this->_args['query_args']['field_id'],
'value' => $this->_args['query_args']['field_value']
)
);
}
$is_no_paging = $this->_args['query_args']['nopaging'] == true;
$this->_args['paging'] = array(
'offset' => $is_no_paging ? 0 : $this->_args['query_args']['offset'],
'page_size' => $is_no_paging ? 999 : $this->_args['query_args']['page_size']
);
$this->_args['sorting'] = array(
'key' => $this->_args['query_args']['order_by'],
'direction' => $this->_args['query_args']['order']
);
// time for hooks
add_action( "gform_pre_render_{$this->_args['target_form_id']}", array( $this, 'populate' ) );
add_action( "gform_admin_pre_render_{$this->_args['target_form_id']}", array( $this, 'populate' ) );
add_action( "gform_pre_submission_filter_{$this->_args['target_form_id']}", array( $this, 'populate' ) );
}
public function populate( $form ) {
foreach( $form['fields'] as &$field ) {
if( $field['id'] != $this->_args['target_field_id'] )
continue;
$entries = $this->get_entries_for_population( $this->_args['source_form_id'] );
$choices = array();
foreach( $entries as $entry ) {
$value = $this->get_entry_value( $entry, $this->_args['value'] );
$label = $this->_args['label'] ? $this->get_entry_value( $entry, $this->_args['label'] ) : $value;
$choices[] = array(
'text' => $label,
'value' => $value
);
}
if( empty( $choices ) ) {
$choices[] = array(
'text' => __( 'There are no options available currently.' ),
'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_entries_for_population( $form_id ) {
return GFAPI::get_entries( $form_id, $this->_args['query_args'], $this->_args['sorting'], $this->_args['paging'] );
}
public function get_entry_value( $entry, $template ) {
$field_id = intval( $template );
if( $field_id )
return rgar( $entry, $field_id );
$form = GFAPI::get_form( $entry['form_id'] );
$template = GFCommon::replace_variables( $template, $form, $entry, false, true, false, 'html' );
return $template;
}
}
# Configuration
new GW_Populate_Entries( array(
'target_field_id' => 1, // the field to be populated with entry data; must be a choice-based field (drop down, radio, checkbox)
'target_form_id' => 449, // the form that contains the field to be populated
'source_form_id' => 414, // the form from which entry data should be retrieved
'value' => '{entry_id}', // specifies the data that should be populated for the choice's 'value'; can be a field ID (i.e. 12) or a 'template' string with merge tag support (i.e. '{entry_id}')
'label' => '{:1.3} {:1.6} ({entry_id})', // same as 'value' but used to populate the label of the choice
'query_args' => array( // specifies which entries should be pulled for display
'status' => 'trash',
'field_id' => '1.3',
'field_value' => 'test',
'order' => 'asc',
'order_by' => '1.3',
'nopaging' => true
)
) );
@Ewect08
Copy link

Ewect08 commented Nov 8, 2016

This is great code, thanks. I do however have a question.

Is it posable to prefill fields based on the selection from the drop down box from the previous entries?

@jstukey
Copy link

jstukey commented Jun 14, 2017

@ccollabgist - im getting an error on $current_user = wp_get_current_user();
Fatal error: Call to undefined function wp_get_current_user() in...

Any thoughts? Did you get the same?

@jstukey
Copy link

jstukey commented Jun 14, 2017

FYI - I resolved the error and got the 'Display Entries Created By Currently Logged In User' working beautifully as defined above. ``

// get the logged in user if(!function_exists('wp_get_current_user')) { include(ABSPATH . "wp-includes/pluggable.php"); } $current_user = wp_get_current_user();

@MadCowWeb
Copy link

I could kiss you for this!! Thank you angry-badger for the config help!
for those looking for the code, you can grab the field info by adding the field into your notification email (just to copy it). and dump it In that config area for "value" and "label".

This was mine:

'target_field_id' => 8,        
'target_form_id' => 3,        
'source_form_id' => 2,        
'value' => '{Name (First):1.3} {Name (Last):1.6}',        
'label' => '{Name (First):1.3} {Name (Last):1.6}', 
'query_args' => array(          
    'order' => 'asc',
    'order_by' => '1.3',
    'nopaging' => true
)

@yozawiratama
Copy link

how can i populate with conditional?
for example there are two dropdown,

  1. users dropdown
  2. bank account dropdown

when user change selected users, it will change filled data populated in bank account.

how to do that? any idea?

@amber-c
Copy link

amber-c commented Jul 13, 2017

The 'text' => __( 'There are no options available currently.' ), was previously working with GF's conditional logic on Submit button but appears to have stopped working.

For example, if you wanted to hide the submit button if the field contains the text There are no options available currently. it doesn't appear to work. Any ideas if something changed in GF that would cause this to not function with the current snippet?

@ejnavav
Copy link

ejnavav commented Sep 4, 2017

Thank you very much for this piece of code and for everyone's contribution. It works pretty much out of the box!
One thing I'm trying to do is add multiple filters but I'm unsure how to achieve this.

I've already added a filter to only display entries originated from current user ('field_id' => 24, 'field_value' => $current_user->user_login) However id like to add an additional filter (e.g. with status 'active') this is an existing field in the form, so that it only displays "active" entries.

Thanks in advance

@thenax
Copy link

thenax commented Sep 14, 2017

I have a link with "idpost" parameter (www.mywebsite.it?idpost=125)
how can I populate dropdown menu with post ID = idpost?

'value' => '$_GET['idpost']' ??

@lion110
Copy link

lion110 commented Oct 15, 2017

Hi, thanks a lot for your great script, I am not able to populate differently label and value tho,

Here's my exact situation:

form A (field 1 customer, field 2 email),
form B (field 1 dropdown list with customer and the value should be its email)

'value' => 2,        // specifies the data that should be populated for the choice's 'value'; can be a field ID (i.e. 12) or a 'template' string with merge tag support (i.e. '{entry_id}')
'label' => 1, // same as 'value' but used to populate the label of the choice

using this configuration the dropdown shows the default values, the form works if I use the same value and label instead.

Any hint? What am I doing wrong?

Thanks a lot guys

@SqueezyDee
Copy link

Hello everyone,

Thank you for this code. I am looking for some help extending it a bit. Here is my situation:

Form 1 - An Admin form to control choices for Form 2.

  • Brand
  • Model
  • Type
  • Capacity

image

I have these fields on an equipment registration form (Form 2). I would like to filter the model when brand is selected based on the Form 1 entries because the equipment model is specific to the brand. Then, once the model is selected the type and capacity can be auto populated from the Form 1 entries.

image

Any help is greatly appreciated!

@MackDS
Copy link

MackDS commented Jan 26, 2018

Firstly great script. I just have one question, can I have multiple 'target_field_id' ?
All the other settings are the same, I just need to repeat this selection
I tried various options but it doesnt work like
'target_field_id' => 152,157,

@yellowstonebum
Copy link

yellowstonebum commented Sep 15, 2018

I'm looking for something like this but for the List Field drop down. I can get it to work for user meta, but not for Gravity Entries:

add_filter( 'gform_column_input_42_1_3', 'business_column', 10, 5 );
function business_column( $input_info, $field, $column, $value, $form_id ) {

  $items = array();
// Get the custom field values stored in the array

// If editing this lookup where you would like to get your data from
// this example loads through all users of the website
$metas = get_users( array( 'role' => 'company' ) );

if (is_array($metas))
{
// in this example we just load the display_name for each user into our drop-down field
foreach($metas as $meta) $items[] = array("value" => $meta->display_name, "text" => $meta->display_name);
}

return array( 'type' => 'select', 'choices' => $items );

}

Any thoughts?

@Captaindrew80
Copy link

How do you change this to alphabetical order? I see :
'order_by' => '1.3
What's that mean? What do I need to change in the config?

Copy link

ghost commented Nov 21, 2018

Somebody has the solution to auto populate fields based on the selection from the drop down box?
@WesternWebDoc commented one year ago this question, and nobody reply it.
Thanks a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment