Using Gravity Forms ‘gform_pre_render’ PHP filter

The gform_pre_render filter in Gravity Forms is executed before a form is displayed and can be used to manipulate the Form Object prior to rendering the form. It is often used in conjunction with other filters such as gform_pre_validation, gform_pre_submission_filter, and gform_admin_pre_render to update the Form Object for use in other places like merge tags in the confirmation and notification.

Usage

To use the gform_pre_render filter, simply add it to your function. To apply to all forms:

add_filter( 'gform_pre_render', 'your_function_name');

To limit the scope to a specific form, append the form id to the end of the hook name:

add_filter( 'gform_pre_render_6', 'your_function_name');

Parameters

  • $form (array): The current form object to be filtered.
  • $ajax (bool): Indicates if AJAX is enabled.
  • $field_values (array): An array of dynamic population parameter keys with their corresponding values to be populated.

More information

See Gravity Forms Docs: gform_pre_render
This filter may not be used in cached pages due to the limitation of caching, which prevents PHP code from running.

Examples

Populate Choices

This example dynamically populates a dropdown, radio button or multi-select field with posts that are in the Business category.

add_filter( 'gform_pre_render', 'populate_choices');
add_filter( 'gform_pre_validation', 'populate_choices');
add_filter( 'gform_admin_pre_render', 'populate_choices');
add_filter( 'gform_pre_submission_filter', 'populate_choices');

function populate_choices($form) {
  if ($form['id'] != 5) {
    return $form;
  }

  // Reading posts for "Business" category
  $posts = get_posts('category=' . get_cat_ID('Business'));

  // Creating item array
  $items = array();

  // Add a placeholder to field id 8, not used with multi-select or radio, will overwrite placeholder set in form editor.

  // your custom code here

  return $form;
}

The function populate_choices is added to the four hooks. In the function, it checks if the form id is 5. If it’s not, the function exits early and returns the form as it is. If it is form 5, it fetches posts from the ‘Business’ category and initializes an empty item array for future use. The function then returns the modified form.