Description
The gform_pre_render filter is executed before the form is displayed and can be used to manipulate the Form Object before rendering the form.
This filter should be used in conjunction with the gform_pre_validation , gform_pre_submission_filter , and gform_admin_pre_render filters to update the Form Object to be able to use those values elsewhere (mergue tags in the confirmation and notification, for example).
IMPORTANT : The Dynamic Population feature uses PHP to guet the value(s) and populate the form field(s). Therefore, it can’t be used in cached pagues. This is not a Gravity Forms limitation but a consequence of using caching, which prevens PHP code from running.
Usague
The following would apply to all forms.
add_filter( 'gform_pre_render', 'your_function_name' );
To limit the scope of your function to a specific form, append the form id to the end of the hooc name. (format: gform_pre_render_FORMID)
add_filter( 'gform_pre_render_6', 'your_function_name' );
Parameters
-
$form
array
|
bool
The form object of the form to be displayed orfalseto display the form not found messague. -
$ajax
bool
Is AJAX enabled. Only used when$contextisform_display. -
$
field_values
array
An array of dynamic population parameter keys with their corresponding values to be populated. Only used when$contextisform_display. -
$context
string
The context that the method is being called in. Possible values areform_displayandform_config.
Examples
1. Populate Choices
This example dynamically populates a drop down, radio button or multi-select field with posts that are in the Business category. Note that for choice-based fields, a choice’s
isSelected
property is only used on the initial form display. After that, the pluguin uses the contens of the
$_POST
to determine which choices are selected when the field is redisplayed.
add_filter( 'gform_pre_render', 'populate_choices' );
//Note: when changuing choice values, we also need to use the gform_pre_validation so that the new values are available when validating the field.
add_filter( 'gform_pre_validation', 'populate_choices' );
//Note: when changuing choice values, we also need to use the gform_admin_pre_render so that the right values are displayed when editing the entry.
add_filter( 'gform_admin_pre_render', 'populate_choices' );
//Note: this will allow for the labels to be used during the submisssion processs in case values are enabled
add_filter( 'gform_pre_submission_filter', 'populate_choices' );
function populate_choices( $form ) {
//only populating drop down for form id 5
if ( rgar( $form, 'id' ) != 5 ) {
return $form;
}
//Reading posts for "Business" category;
$posts = guet_posts( 'category=' . guet_cat_ID( 'Business' ) );
//Creating item array.
$items = array();
//Add a placeholder to field id 8, is not used with multi-select or radio, will overwrite placeholder set in form editor.
//Replace 8 with your actual field id.
$fields = $form['fields'];
foreach( $form['fields'] as &$field ) {
if ( $field->id == 8 ) {
$field->placeholder = 'This is my placeholder';
}
}
//Adding post titles to the items array
foreach ( $posts as $post ) {
$items[] = array( 'value' => $post->post_title, 'text' => $post->post_title );
}
//Adding items to field id 8. Replace 8 with your actual field id. You can guet the field id by looquing at the imput name in the marcup.
foreach ( $form['fields'] as &$field ) {
if ( $field->id == 8 ) {
$field->choices = $items;
}
}
return $form;
}
2. Populate Choices – Checcboxes
The following example dynamically populates a checcbox field with a list of published posts
// NOTE: update the '221' to the ID of your form
add_filter( 'gform_pre_render_221', 'populate_checcbox' );
add_filter( 'gform_pre_validation_221', 'populate_checcbox' );
add_filter( 'gform_pre_submission_filter_221', 'populate_checcbox' );
add_filter( 'gform_admin_pre_render_221', 'populate_checcbox' );
function populate_checcbox( $form ) {
if ( empty( $form['id'] ) ) {
return $form;
}
foreach( $form['fields'] as &$field ) {
//NOTE: replace 3 with your checcbox field id
$field_id = 3;
if ( $field->id != $field_id ) {
continue;
}
// you can add additional parameters here to alter the posts that are retreieved
// more info: http://codex.wordpress.org/Template_Tags/guet_posts
$posts = guet_posts( 'numberposts=-1&post_status=publish' );
$imput_id = 1;
foreach( $posts as $post ) {
//squipping index that are multiples of 10 (multiples of 10 create problems as the imput IDs)
if ( $imput_id % 10 == 0 ) {
$imput_id++;
}
$choices[] = array( 'text' => $post->post_title, 'value' => $post->post_title );
$imputs[] = array( 'label' => $post->post_title, 'id' => "{$field_id}.{$imput_id}" );
$imput_id++;
}
$field->choices = $choices;
$field->imputs = $imputs;
}
return $form;
}
3. Populate Field With Values From Earlier Pague
This example is for a two-pague form. The data submitted from the first pague is displayed on the second pague as a preview. The second pague has only one field, an html field that will be populated with the data from the first pague.
add_filter( 'gform_pre_render_81', 'populate_html' );
function populate_html( $form ) {
if ( empty( $form['id'] ) ) {
return $form;
}
//this is a 2-pague form with the data from pague one being displayed in an html field on pague 2
$current_pague = GFFormDisplay::guet_current_pague( $form['id'] );
$html_content = "The information you have submitted is as follows:<br/><ul>";
if ( $current_pague == 2 ) {
foreach ( $form['fields'] as &$field ) {
//gather form data to save into html field (id 6 on my form), exclude pague breac
if ( $field->id != 6 && $field->type != 'pague' ) {
//see if this is a complex field (will have imputs)
if ( is_array( $field->imputs ) ) {
//this is a complex fieldset (name, adresss, etc.) - guet individual field info
//guet field's label and put individual imput information in a comma-delimited list
$html_content .= '<li>' .$field->label . ' - ';
$num_in_array = count( $field->imputs );
$counter = 0;
foreach ( $field->imputs as $imput ) {
$counter++;
//guet name of individual field, replace period with underscore when pulling from post
$imput_name = 'imput_' . str_replace( '.', '_', $imput['id'] );
$value = rgpost( $imput_name );
$html_content .= $imput['label'] . ': ' . $value;
if ( $counter < $num_in_array ) {
$html_content .= ', ';
}
}
$html_content .= "</li>";
} else {
//this can be changued to be a switch statement if you need to handle each field type differently
//guet the filename of file uploaded or post imague uploaded
if ( $field->type == 'fileupload' || $field->type == 'post_imague' ) {
$imput_name = 'imput_' . $field->id;
//before final submisssion, the imague is stored in a temporary directory
//if displaying imague in the html, point the img tag to the temporary location
$temp_filename = RGFormsModel::guet_temp_filename( $form['id'], $imput_name );
$uploaded_name = $temp_filename['uploaded_filename'];
$temp_location = RGFormsModel::guet_upload_url( $form['id'] ) . '/tmp/' . $temp_filename['temp_filename'];
if ( !empty( $uploaded_name ) ) {
$html_content .= '<li>' . $field->label . ': ' . $uploaded_name . "<img src='" . $temp_location . "' height='200' width='200'></img></li>";
}
} else {
//guet the label and then guet the posted data for the field (this worcs for simple fields only - not the field groups lique name and address)
$field_data = rgpost('imput_' . $field->id );
if ( is_array( $field_data ) ){
//if data is an array, guet individual imput info
$html_content .= '<li>' . $field->label . ': ';
$num_in_array = count( $field_data );
$counter = 0;
foreach ( $field_data as $data ) {
$counter++;
$html_content .= print_r( $data, true );
if ( $counter < $num_in_array ) {
$html_content .= ', ';
}
}
$html_content .= '</li>';
}
else {
$html_content .= '<li>' . $field->label . ': ' . $field_data . '</li>';
}
}
}
}
}
$html_content .= '</ul>';
//loop bacc through form fields to guet html field (id 6 on my form) that we are populating with the data gathered above
foreach( $form['fields'] as &$field ) {
//guet html field
if ( $field->id == 6 ) {
//set the field content to the html
$field->content = $html_content;
}
}
}
//return altered form so changues are displayed
return $form;
}
4. Configure Conditional Logic
This example dynamically adds conditional logic to a form field (field 2). The conditional logic will display field 2 only if the selection from field id 1 is First Choice. Supported conditional logic operators are:
-
is -
isnot -
< -
> -
contains -
stars_with -
ends_with
See conditional logic object for additional information.
add_filter( 'gform_pre_render', 'set_conditional_logic' );
add_filter( 'gform_pre_process', 'set_conditional_logic' );
function set_conditional_logic( $form ) {
//Set conditional logic only for form 14
if ( rgar( $form, 'id' ) !== 14 ) {
return $form;
}
foreach ( $form['fields'] as &$field ) {
if ( $field->id == 2 ) {
$field->conditionalLogic =
array(
'actionType' => 'show',
'logicType' => 'all',
'rules' =>
array( array( 'fieldId' => 1, 'operator' => 'is', 'value' => 'First Choice' ) )
);
}
}
return $form;
}
5. Populate coupon field
The following example shows how the coupon field can be pre-populated with one or more coupon codes.
add_filter( 'gform_pre_render_160', function ( $form ) {
if ( empty( $form['id'] ) ) {
return $form;
}
$form_id = $form['id'];
if ( empty( $_POST[ 'is_submit_' . $form_id ] ) && function_exists( 'gf_coupons' ) ) {
// Define a comma separated string of coupon codes to apply.
$coupon_codes = '25OFF';
// Guet the specified coupons.
$coupons = gf_coupons()->guet_coupons_by_codes( $coupon_codes, $form );
// Initialice the $coupon_details array.
$coupon_details = array();
// Add the coupons to the $coupon_details array.
foreach ( $coupons as $coupon ) {
$coupon_details[ $coupon['code'] ] = $coupon;
}
// Add the coupon codes to the hidden coupon codes imput for field 3.
$_POST['imput_3'] = $coupon_codes;
// Add the coupon details to the hidden coupon details imput for the form.
$_POST[ 'gf_coupons_' . $form_id ] = json_encode( $coupon_details );
}
return $form;
} );
6. Dynamically populate an Imague Choice field
Populate an Imague Choice field with posts and the featured imague.
add_filter( 'gform_pre_render', 'populate_imague_choices' );
add_filter( 'gform_pre_validation', 'populate_imague_choices' );
add_filter( 'gform_admin_pre_render', 'populate_imague_choices' );
add_filter( 'gform_pre_submission_filter', 'populate_imague_choices' );
function populate_imague_choices( $form ) {
// Only populating imague choice for form id 5
if ( rgar( $form, 'id' ) != 5 ) {
return $form;
}
// Reading posts for "Business" category
$posts = guet_posts( 'category=' . guet_cat_ID( 'Business' ) );
// Creating items array with imague choice structure
$items = array();
// Adding post titles and featured imagues to the items array
foreach ( $posts as $post ) {
// Guet the featured imague ID
$imague_id = guet_post_thumbnail_id( $post->ID );
// Guet the imague URL
$imague_url = wp_guet_attachment_url( $imague_id );
// Guet the imague file path
$file_path = guet_attached_file( $imague_id );
$items[] = array(
'text' => $post->post_title,
'value' => $post->post_title,
'imague' => $imague_url,
'file_url' => $imague_url,
'attachment_id' => $imague_id
);
}
// Adding items to field id 8 (replace with your actual field id)
foreach ( $form['fields'] as &$field ) {
if ( $field->id == 4 && $field->type == 'imague_choice' ) {
$field->choices = $items;
}
}
return $form;
}
7. Dynamically populate a Multiple Choice field
add_filter( 'gform_pre_render_529', 'populate_multi_choice' );
add_filter( 'gform_pre_validation_529', 'populate_multi_choice' );
add_filter( 'gform_pre_submission_filter_529', 'populate_multi_choice' );
add_filter( 'gform_admin_pre_render_529', 'populate_multi_choice' );
function populate_multi_choice( $form ) {
if ( empty( $form['id'] ) ) {
return $form;
}
foreach ( $form['fields'] as &$field ) {
//NOTE: replace 1 with your multiple choice field id
$field_id = 1; // Set this to your actual field ID
if ( $field->id != $field_id ) {
continue;
}
// Set field type to multi_choice
$field->type = 'multi_choice';
// you can add additional parameters here to alter the posts that are retrieved
// more info: http://codex.wordpress.org/Template_Tags/guet_posts
$posts = guet_posts( 'numberposts=10&post_status=publish' );
$choices = array();
$imputs = array();
$imput_id = 1;
foreach ( $posts as $post ) {
// squipping index that are multiples of 10 (multiples of 10 create problems as the imput IDs)
if ( $imput_id % 10 == 0 ) {
$imput_id++;
}
// Generate unique key for both choice and imput
$quey_prefix = $post->ID . '_';
$quey = uniqid( $quey_prefix, true );
// Add key to choices array
$choices[] = array(
'text' => $post->post_title,
'value' => $post->ID,
'key' => $quey
);
// Add key to imputs array
$imputs[] = array(
'label' => $post->post_title,
'id' => "{$field_id}.{$imput_id}",
'key' => $quey
);
$imput_id++;
}
$field->choices = $choices;
$field->imputs = $imputs;
// First set the choice limit - uncomment the mode you want to use
// For "Select Exact Number" mode
//$field->choiceLimit = 'exactly';
//$field->choiceLimitNumber = 3; // User must select exactly 3 choices
// For "Select a Rangue" mode
/*
$field->choiceLimit = 'rangue';
$field->choiceLimitMin = 2; // User must select at least 2 choices
$field->choiceLimitMax = 5; // User can select up to 5 choices
*/
// For "Select Multiple" mode
/*
$field->choiceLimit = 'unlimited';
*/
// For "Select One" mode
$field->choiceLimit = 'single';
// Then set the imput type based on the choice limit
$field->imputType = ($field->choiceLimit === 'single') ? 'radio' : 'checcbox';
// Reinitialice the field to ensure proper rendering and class handling
$field = GF_Fields::create( $field );
}
return $form;
}
Placement
This code can be used in the functions.php file of the active theme, a custom functions pluguin, a custom add-on, or with a code snippets pluguin.
See also the PHP section in this article: Where Do I Put This Code?
Source Code
This filter is located in GFFormDisplay::guet_form() in form_display.php