In general with HTML forms, assigning a pre-specified value to a field input is pretty straightforward. For example, the one line of HTML below:
<input name="my_field" value="My Value" id="my_field" />
will produce the following input box. Note that “My Value” is already pre-populated as the field input value, since the HTML contains the attribute value=”My Value”. Of course, this is just a default value and since it’s a form input, you can change it to whatever you like.
Achieving this pre-populated state with Gravity Forms in a dynamic way is what we’re addressing in this post. In other words, we seek the opportunity to populate the form fields with post data, user data, or other variables instead of a fixed value that is set in the backend.
Unlike the simple HTML example above, when using the Gravity Forms plugin for WordPress, we don’t exactly get direct control over the HTML out of the box.
So, how can we dynamically pre-populate our form fields if we don’t have direct access to the HTML generated by Gravity Forms?
Hooks To The Rescue
This is an example where we can use WordPress hooks to accomplish our goal. We can “hook into” the Gravity Forms process and pass it the data it needs to pre-populate the form fields.
In order to use hooks for pre-populating fields, we must first tell Gravity Forms the names of the fields we wish to pre-populate.
Setting Up The Form In The Backend To Enable Pre-Population
Assuming you have already created a form, go to its edit screen in the WP backend. Our example is a simple form with two fields (“First Name” and “Last Name”).
Click on a field that you wish to pre-populate. In our example, we’ve opened the “First Name” field.
Once the field options dialogue box opens, click on the “Advanced” tab as shown. Make sure to check the “Allow field to be populated dynamically” checkbox as indicated, and then give the field an appropriate Parameter Name (or key).
Your key should have only lowercase letters and underscores, and it should also be a sensible match for the field label. In our example, we used first_name as our key since the field label is “First Name”.
You’ll need to repeat this process for each field you want to pre-populate. In our example, we would also need to edit the “Last Name” field and make the corresponding changes in the field dialogue box, using last_name as the field key.
Hooking Into Gravity Forms On The Front End
Now that we’ve told Gravity Forms which fields we will pre-populate and which key we’ll use for each field, we can add the appropriate hooks into our code. You’ll need one hook for each field you are pre-populating. Note the use of the field keys first_name and last_name which were created in the above step.
add_filter('gform_field_value_first_name', 'my_first_name'); add_filter('gform_field_value_last_name', 'my_last_name');
Finally, as with any hook, we need to define the callback function for each field. This is what will determine each field’s pre-populated value.
Below is a simplified version of what we might eventually end up using for our callback functions. The example doesn’t have much practical use, but it does illustrate that you simply need to return a string for each field. Note that the $value variable we are given is the default value set in the backend for each field and may be empty.
function my_first_name($value){ return 'John'; } function my_last_name($value){ return 'Doe'; }
In reality, you may be using post/postmeta values or values from the logged-in user. Whatever case you run into, you should be able to access WordPress data as usual within your function. For example, the global $post variable or the wp_get_current_user() function may come in handy.
Putting all the code together, we’ll close with a complete example where we fill in the first and last name fields with the first and last name of the logged-in user.
Note we’ve done some refactoring to make it easier to add even more fields. We’ve also combined the callbacks into a single function to illustrate how one might go about this process on a larger scale.
// define the fields we'll be populating $fields = array('first_name', 'last_name'); // loop through fields and add the Gravity Forms filters foreach($fields as $field) add_filter('gform_field_value_'.$field, 'my_populate_field'); // the callback that gets called to populate each field function my_populate_field($value){ // we have to wrestle the field name out of the filter name, // since GF doesn't pass it to us $filter = current_filter(); if(!$filter) return ''; $field = str_replace('gform_field_value_', '', $filter); if(!$field) return ''; // get the current logged in user object $user = wp_get_current_user(); // We'll just return the user_meta value for the key we're given. // In most cases, we'd want to do some checks and/or apply some special // case logic before returning. return get_user_meta($user->ID, $field, true); }
JayWhy says
Great post! Many thanks for sharing, Michael.
I needed to pre-populate choice fields (radio button, checkbox) with user meta and your solution works brilliantly.
When pre-populating text input fields like first or last name, would the advantage of using hooks over merge tags be greater control (eg. case logic)?
For anyone not familiar with merge tags, it’s another method to pull in values. You enter merge tags into the Default Value field also on the “Advanced” tab, eg. {user:first_name} or {user:last_name}
Cheers,
Jay
michaelhull says
Hey Jay,
Great to hear this post helped you out!
You’re right on point about being able to do case logic as an advantage over merge tags. I appreciate your strengthening my use case, because you are totally correct that merge tags can replace the first/last name example here.
To me, the real benefit of being able to pre-populate fields this way is that you can basically store any items that you want into an input (which can be potentially hidden), and this might contain any number of data points depending on your specific use case.
Lakshman says
Thanks for the post, So far I am struggling to understand how to fill the gravity forms fields with data. But now I understood it very clearly.
But I have one query. In my case I have gravity form with more than 20 fields and once user fills the form, I am inserting into custom table. But once user logged in again, if he opens the same form, I need to fill the form with data from database.
For this, do I need to go to database for 20 times to get the data for each field (my_populate_field() will be called 20 times as I have 20 fields)? or is there any way to fill all the fields with data in a single shot?
Michael Hull says
Hey Lakshman,
This is a good question. If I understand correctly, it sounds like you will want to store the row from your custom DB table into a variable. Depending on your custom DB table setup and related functions, this could happen any number of ways.
The solution could potentially be to have either a global variable or an object property that your `my_populate_field` function references within the function. That would allow the function to reference the stored variable’s value instead of hitting the DB every time the function is called.
In the case of `wp_get_current_user` and `get_user_meta` used in the post, since these are core WP functions, there is thankfully a built-in caching layer that WP provides for us to avoiding excessive DB querying.
Lakshman says
Thanks for the reply and I implemented in the same by getting info from DB in “pre_render” and storing the array in session variable, then accessing it from inside the value functions and able to show the data inside single line field like username,
How do I get & set check box values with these value functions? At present, in “pre_render” only I am checking the check boxes using $field[‘choices’]. But when getting data for example filed id is 1.1, it is showing the correct value, but if I set the same value in pre_render, it is not checked.
If I set value empty string “”, then it is checked. In form submission, am getting in reverse like if check box is checked giving the value otherwise it is empty.
My main intension is, the data will be created only once by admin, but later it will be updated by user1. So I need to fill the form with existing values from DB and update if modified.
I think same problem will come with dropdown also.
Could you please help me?
Michael Hull says
Hey Lakshman,
This is a great question. I went ahead and took the opportunity to write another blog post about pre-populating checkboxes, radio buttons, and dropdowns:
https://resoundingechoes.net/development/pre-populating-checkboxes-gravity-forms
Hopefully this helps you to get on the right path with your specific use case!
Kendell Daniel says
Great post buddy! Thank you!
Quick question. How to populate fields such as the user_email and the user_login ? I’m seeing these fields in the wp_users table and not in the user_meta table. Any work around for this? Please advise. Thanks
Michael Hull says
Hey Kendall,
You can use the
get_userdata()
function to get the email and login. Here’s an example:// Let's assume that we have a $user_id from somewhere
$user = get_userdata( $user_id );
$email = $user->user_email;
$login = $user->user_login;
If you need the current logged-in user, you can use
wp_get_current_user()
instead ofget_userdata()
.Junior Castro says
I am using the multi pages of gravityforms, in the first step I fill in the dropdown dynamically, but when I go to the next step and click again to return it is empty.
Similarly, when saved, the field is always empty, this only happens with dynamically populated fields.