Suppose you want to create a form that allows the user to enter its name. This is a common requirement for many forms and for this reason Gravity Forms has an advanced Name field just for this purpose. As mentioned in a previous article, the Name field is a multiple input field, similarly to the Address and checkbox fields.
We will discuss two methods for populating the Name field, but before we do that let’s write a function that will retrieve the logged-in user’s first and last name.
Retrieving user meta information
WordPress stores information about the currently logged-in user in an instance of the WP_User class. Using this object we can retrieve any meta data associated with the logged-in user, as shown below:
So, to obtain the current user’s first and last name, we can write:
Now let’s see how this function can be used to populate a Gravity Forms Name field with the user’s data.
Method 1 – using dynamic population parameters
This is the simplest approach and relies on the gform_field_value_$parameter_name filter, which is executed before displaying each field and can be used to dynamically populate fields with a default value.
To use this method, select the option “Allow field to be populated dynamically” in the “Advanced” tab of the Name field and enter the parameter names for the “First” and “Last” components of the name. We shall assume that the parameter names are “first_name” and “last_name”. Note that this applies to a Name field whose “Name Format” property is set to “Normal”; for “Simple” and “Extended” fields, the number of parameters is 1 and 4, respectively.
Then add the following code to your theme’s
Method 2 – setting field default value directly
This method is more complex but gives us more insight into the internals of the Gravity Forms Name field. First of all, we shall write a function that takes a string or array parameter and populates a Name field:
When the “Name Format” of the field is set to “Simple”, pass a string containing the full name. When the “Name Format” is “Normal” or “Extended”, pass an array with keys “first”, “last”, “prefix” (for “Extended” only), “suffix” (for “Extended” only). If you pass such an array for a “Simple” field, the first and last name components will be joined together to form the full name.
Now let’s see how this function can be used to populate the Name field. We shall use the gform_pre_render filter, which is executed before the form is displayed and can be used to manipulate the Form Object prior to rendering the form.