Skip to content

Instantly share code, notes, and snippets.

@travislopes
Created December 11, 2015 02:32
Show Gist options
  • Save travislopes/f3369cbb61fca9252c13 to your computer and use it in GitHub Desktop.
Save travislopes/f3369cbb61fca9252c13 to your computer and use it in GitHub Desktop.
Populate form fields with values from a previous form entry
<?php
/**
* Gravity Forms Easy Form Population
*
* Populate form fields with values from a previous form entry.
*
* @version 1.0
* @author Travis Lopes <[email protected]>
* @license GPL-2.0+
* @link http://travislop.es/
*/
class Gravity_Forms_Easy_Form_Population {
public function __construct() {
add_filter( 'gform_pre_render', array( $this, 'populate_form' ) );
}
public function populate_form( $form ) {
/* If the entry ID parameter is not set, return the form. */
if ( ! rgget( 'entry_id' ) ) {
return $form;
}
/* Get the entry and its form. */
$original_entry = GFAPI::get_entry( rgget( 'entry_id' ) );
$original_form = GFAPI::get_form( $original_entry['form_id'] );
$field_values = array();
/* Loop through the original form's fields and push set values to field values array. */
foreach ( $original_form['fields'] as $field ) {
/* If this field has multiple inputs, loop through them. */
if ( $field->inputs ) {
foreach ( $field->inputs as $input ) {
if ( $input['name'] ) {
$field_values[ $input['name'] ] = rgar( $original_entry, $input['id'] );
}
}
} else {
if ( $field->inputName ) {
$field_values[ $field->inputName ] = rgar( $original_entry, $field->id );
}
}
}
/* Add field values to current form. */
foreach ( $form['fields'] as &$field ) {
/* If this field has multiple inputs, loop through them. */
if ( $field->inputs ) {
foreach ( $field->inputs as &$input ) {
if ( $input['name'] && rgar( $field_values, $input['name'] ) ) {
$input['defaultValue'] = rgar( $field_values, $input['name'] );
}
}
} else {
if ( $field->inputName && rgar( $field_values, $field->inputName ) ) {
$field->defaultValue = rgar( $field_values, $field->inputName );
}
}
}
/* Return the form. */
return $form;
}
}
if ( class_exists( 'GFForms' ) ) {
new Gravity_Forms_Easy_Form_Population();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment