Pre-populate Fields using Gravity Forms

Inside a computer

Gravity Forms is my new favourite plugin and for good reason. It is truly limitless and is the best plugin in its field.

With that said, I thought I’d share how I recently used it to build a form that would be pre-populated with the user’s information (like name, email address, shipping address and phone number) so that they could place an order for marketing materials to be sent to them.

Collect the information

If you want to use fields that are already included in the standard WordPress user profile, like name, or email address, then you’ll just need to use a function to pull that information from an existing database entry. However, if you want to collect extra information, such as an address, shipping preference or really, anything you want, then you’ll need to create extra fields where the user can enter this data.

Collect new data

In order to collect new data, we can write a function to add a new section to the User Profile page, where people can enter their information. I’m going to show you using the code that I wrote for the project that I was working on when I needed this.

This code adds the new section to the page and creates several different fields for all the information that we want to collect. Each field has a unique identifier, so that we can pull each piece of information in to the form separately.

This function should be pasted into your functionality plugin, or functions.php if you don’t have one (in which case, I suggest you spend 10 minutes and create one).

In the first function, we created a table to display on the page, and each line in the table has a unique identifier for the field (such as address_line_1 or full_name), displays the existing value from the database if there is one and displays a description to help the users fill out the fields.

The second function saves the information to the database, but only if the user has the privilege to do so, as an added security measure.

It should be easy to deduce how the code works and has been replicated several times over to create all the fields, so cut and edit what you need to save the information as you need it.

Populate the form with the data

Now that you’ve collected the information from your users, you want to set up your Gravity Form so that it pulls the information from each user’s profile when they pull up the form.

You can do this by creating special filters that Gravity Forms recognises. All these filters start with “gform_field_value_” and then have the same unique identifiers that we created in the first step. For example, the filter name for the full_name field is gform_field_value_full_name. Copy the code below and adjust all the filters for the specific fields that you created in the function above. This code goes in the same functions.php file or functionality plugin that we used above.

Configure Gravity Forms

Everything is now set up to have Gravity Forms receive the data, but you need to tell it where you want this data to appear.

How to Pre-populate fields in Gravity FormsSo start off by either creating a new form, or editing an existing one. Find the fields where you want the data to appear and edit them. Click on the Advanced tab and check the box for Allow this Field to be Populated Dynamically. In the field labeled Parameter Name, enter the unique identifier that we created in the first function and then reused in the second function. In this example, the parameter would be full_name.

Save your form and try it out. Go to the form and see whether it pulls in your information (make sure that your profile contains the information you’re trying to fill the form with, especially if you created custom fields).

What unique ways have you used this trick to fill out forms and save some time? If you’re having trouble getting this to work, let me know and I’ll see if I can help you.

Try it yourself

48 thoughts on “Pre-populate Fields using Gravity Forms”

  1. Simone says:

    Hello David, i came to your very interesting post via Google.

    Im exactly looking for that but simply i wanna prepopulate a field in a Gravity Forms form with the email address of current logged-in user.

    What is the code to use in functions.php?
    I need the use of User Registration Add-on?

    Thanks in advice.

    1. All the code is in this post. Just keep the email field and delete all of the other fields I added, like name and address. No need for any add-ons.

    2. Nathan says:

      You don’t really even need to do all of this. Just go to the Form Editor, click the Advanced tab on the field you want to prepopulate, and then under “Default Value” enter {user:user_email} – this is a built in feature (maybe not when the post was originally published here but I believe so) that requires no custom coding. You can also do {user:anymetafieldkey} for any other information you store along with a user’s profile.

      1. Nathan, I don’t think that this method was available when I wrote this, but that’s an awesome shortcut. Thanks for sharing. Certainly makes doing this a whole lot easier!

        1. Nathan says:

          Quite possibly they weren’t! Gravity Forms is great, like you said, and one reason is they’re always improving. Now if Gravity Charge would ever become a reality…

  2. Simone says:

    Thanks Dave for the quick reply, i will try it! As i see from the code i just need the second snippet as the first one is only for adding these extra fields: address, city, state, zip code, country, phone.

    1. Yes, good point. And you can eliminate the unnecessary (extraneous) fields from the first snippet.

  3. Simone says:

    Well thanks Dave. Another question even is not related to this subject. Do you know a way to set a max upload size for file upload field? Incredibly Gravity Forms miss that…

    Maybe it could be done in functions.php too but i don’t figure how and what code to use.

    For example if can be set a max upload size of 5mb, in the form submission if one tries to upload a file that is more huge a warning message will be displayed.

    Thanks again!

    1. Simone, to the best of my knowledge and from the research I’ve done, this isn’t possible because Gravity Forms uses a PHP uploaded and the form doesn’t know the file size until the upload is complete. There is talk of them revamping that functionality, but I haven’t seen anything on it yet.

  4. Simone says:

    After some Googling i came to this post http://zzlatev.com/gravity-forms-upload-limits/
    Maybe could be the solution?

    1. Yes, it seems that the snippet on that site may be for exactly what you need.

  5. toni becker says:

    Hy dave used your code and works like charme. Another question is to save the user meta in user profile. Do you have some snippets? Would be great. Greetings

    1. I’m not sure what you’re wanting to save? The user profile already manages the user’s name, email address etc. and this allows you to add extra information to their profile, which you can then pull into a Gravity Form.

  6. Duncan says:

    Hi Dave,

    Thanks for this great information. I’m new to WordPress and am trying to get this going but run into this error when I attempt to activate the plugin:

    Parse error: syntax error, unexpected ‘/’ in /Applications/MAMP/htdocs/wordpress/wp-content/plugins/my-functionality-plugin/my-functionality-plugin.php on line 22

    Here is my line 22:

    <input type="text" name="address_line_1" id="address_line_1" value="ID ) ); ?>” class=”regular-text” />

    What am I missing?

    Thanks in advance,

    1. You’re missing a closing double quote on the value attribute. Start there and see if that does it. Also, not sure if the way you pasted your code cut off the opening php tag, but make sure that’s in place as well, since you have a closing tag (?>) in there.

  7. dave cousins says:

    Hi Dave-

    This looks great! Here’s a question for you- I am using CIMY extra fields for additional bio form fields (wish I’d found your tutorial first)- you can pull extra field info by using something like this:

    $value = get_cimyFieldValue(user_id, field_name);

    DO you think its possible to use this with gravity forms to prepopulate the fields?

    Thanks!

    Dave

    1. I’m afraid I don’t have time to review and do it myself, but I would certainly think so.

  8. dave cousins says:

    Hi David-

    Another quick question for you: using your custom user profile fields created above, would it be possible to hide or show a message or link based on if there is a value in the profile field for the current user?

    Thanks,

    Dave

    1. Yes, I believe so. You could create a hidden field that pulls in the information from theit user profile and then create the message/link that you want to show or hide and set the conditional logic such that it only shows/hides if the field is or is not blank.

  9. Brad Trivers says:

    Great post! the “__get” magic method for accessing custom user meta was particularly enlightening. Here is another take on how to pre-populate a form from user metadata without having to add a filter for each field.

    Use the gform_pre_render filter to target each form to prepopulate by appending the form id to the end of the filter. The prepopulate function just looks for cases where the field’s inputName is not blank (i.e. the form field has been set up for pre-population), and then assumes that the inputName matches the user meta field name.

    `add_filter(“gform_pre_render_20″, “mf_prepopulate_form_from_user_meta”);
    add_filter(“gform_pre_render_21″, “mf_prepopulate_form_from_user_meta”);
    function mf_prepopulate_form_from_user_meta($form) {
    global $current_user;

    foreach($form[“fields”] as &$field) {
    if($field[“inputName”] != “”) {
    $_GET[$field[“inputName”]] = $current_user->__get($field[“inputName”]);
    }
    }

    return $form;

    }`

    Another though – if you wanted to populate a form from multiple sources (i.e. not just custom user metadata) then you could prefix each inputName with a data source indicator and then use this to determine what source to grab the inputName from).

    1. stefanie says:

      Hi Brad,
      Could you possibly elaborate on populating the fields from multiple sources?

      1. Not sure what you mean by that. Do you mean adding information from somewhere other than the user’s profile information?

        1. stefanie says:

          Yes, we are going to have an external MS SQL database that will hold the records of each customer. I want to use this type of system you created so that when they enroll on the website, they can input their acccount number and then the form will prepopulate with the information we have on them already. From there we can let them register.

          1. I’m sure you can, but it’s beyond the scope of this tutorial. You’d need to hire a developer to do that work.

      2. Brad Trivers says:

        For example you could prefix the inputName with an identifier that indicates where to get the data from to pre-populate. e.g. Use a double underscore to separate the prefix from the inputName – customusermeta__address_line_1, customusermeta__address_line_2, postmeta__productsku, postmeta__productname, etc.

        Then you could explode(“__”, $field[“inputName”]) and check the first value in the resulting array to see where to get the data from. If postmeta then populate the $_GET by getting metadata from a post (whose id you would have to get from somewhere like a $_GET set in the URL), and if customusermeta then use $current_user.

        I’m on a tablet right now but will try to post a link to some sample code later.

        1. Brad Trivers says:

          I used a technique like this to populate the form that appears when the link “Click Here If This Person’s Info Is Incorrect” is clicked for People records on the site below.

          http://marconf.ca/people/maclean-janice-a/

          As an aside I wish that Gravity Forms could be loade by Ajax but no luck with that yet.

          1. stefanie says:

            Thank you Brad, looking forward to seeing the sample code. Your example looks really fantastic and it seems to use the same logic that i’m trying to accomplish. In your case, where is your data being pulled from? So happy I found Dave’s thread and your extra input. I finally feel like I can wrap my mind around around gravity form’s functions. Really appreciate you guys taking the time.

          2. stefanie says:

            Hi Brad, do you think you’ll find any time to post sample code? Thank you, hope you had a nice weekend :)

        2. Brad Trivers says:

          Ok, so I just whipped some sample code together (although I didn’t test it). This populates from “usermeta”, “personmeta” or “organizationmeta” depending on the inputName prefix, and uses a double underscore delimiter to separate this prefix from the meta field name. Usermeta is populated from the currently logged in user’s information, personmeta comes from custom fields for posts of type “people”, and organizationmeta comes from fields for posts of type “organizations”. It checks the post type too, so the fields are only pre-populated if a post of the proper type is being viewed, and form “25” (replace with your form ID) can be reused for multiple post types. You can find the code here:

          http://pastebin.com/JHaSJJaa

          1. stefanie says:

            Really appreciate it, Brad!

  10. passatgt says:

    You can use the Default value field with merge tags, so you don’t need to bother with php codes:

    {user:first_name}
    {user:last_name}

    and so on…

  11. stefanie says:

    Hi Dave,
    I tried putting this code in the functionality plugin I created, but I keeps deactivating saying that there is a fatal error on this line:
    <input type="text" name="address_line_1" id="address_line_1" value="ID ) ); ?>” class=”regular-text” />
    Parse error: syntax error, unexpected ‘/’

    Should I be editing this anywhere?
    Thank you!
    Stefanie

    1. The code won’t paste properly in the comments, so I can’t see any issues with it. Use a service like Pastebin and paste the link to your error here.

      1. stefanie says:

        I removed the “/” from $user-/>ID and it works great now. Is that ok?

        1. Yes, that shouldn’t be in there. It should just be $user->ID

  12. Sam says:

    Nice Article. Very helpful. Is there a way to output the user’s first and last name in the “simple name format” field instead of their username?

    1. You could just concatenate their first and last names from their profile and output that to the simple name format field, instead of separately as first and last names.

  13. Brent says:

    Wondering if anyone has a quick example of how to do this with a custom post type and custom field.
    I have a gravity form that submits part of it’s data to create a user profile (which this tutorial explained very easily), and parts of the same form submit to a custom post type.

    Ideally, when a user logs into the site and visits the same form, I would like to pre-populated the fields with data from the users profile and from the custom post type field(s). Then the user could change existing values and hit update and it would update the profile and the custom post associated with the profile.

    I was able to do this with the custom profile fields but not sure how I would do it with a custom post type and custom meta field.

    Any Advice?

    1. Brent,

      This will work on a custom post type just as easily as on a page or post. I’m confused what you mean in your second paragraph however, where you say that you want the form pre-filled with info from the custom post type fields. Adding information from the user’s profile will work the same, but I’m not sure what you mean by pulling in information from the custom post type fields. Why would you need to do that?

  14. daniel says:

    Hi Dave, because I have the same question, I will respond for him, he had probably created a CPT form before , people submitted some data there and he wants to create another Custom post type form which will use the data from previous CPT form,
    Example: I have Custom post type for girls named “portfolio”, girls insert their data as name, surname, country, city , age, weight, height ecc.
    When they submit the form it creates a new portfolio page with their data, the same girl will want to ask for a job, so she comes to fullfill another Custom post type form for example “job” with questions what the job should looks like, because the second form she would use more times I would like the logged in girl save from inserting the same data as she has already inserted in the portfolio form which she will submit only once, so I want the wordpress to recognize her email or her user ID and to fullfill some portfolio data fields for her.

  15. daniel says:

    But I think that @Brad Trivers have already responded , I will take a look at his code tomorrow

  16. Daniel says:

    Dave, do you happily know how can we use it with buddypress member profile fields? Can you show us one profile field example ?

    1. The first part would be the same. I’ve never worked with BuddyPress, but you’d need to find a way to apply that CSS class to the profile field in question.

  17. Daniel says:

    `//Buddypress prepolute phone
    add_filter(“form_field_value_phone”, “populate_phone”);
    function populate_phone() {
    $current_user = wp_get_current_user();
    $current_user_id = $current_user->ID;
    $phone = bp_profile_field_data( array(‘user_id’=>$current_user_id,’field’=>’phone’ ));
    return $phone;
    }`
    Dave similarly should look the code for buddypress, but it doesn’t give me nothing, about CSS class: I don’t get what you mean, I don’t want to create buddypress fields, they are already created, I want only pre populate already created profile fields in gravity forms when user logged in.

    1. I apologise. I thought this comment was for a different tutorial. The changes that you’d have to make would involve pulling in the BuddyPress information instead of the WordPress profile information as I demonstrated. Again, I haven’t worked with BuddyPress, so I don’t know how to do that off-hand.

  18. Daniel says:

    For somebody who wants also pulling the buddypress profile fields I got that working with this code: `add_filter(“gform_field_value_city”, “populate_city”);
    function populate_city($value){
    global $current_user;
    get_currentuserinfo();
    return xprofile_get_field_data(‘city’, $current_user->ID);
    }` and parameter name = city

  19. RITESH says:

    I have populate a dropdown dynamically using the gform_pre_render hook. I have multi page form. The dropdown gets its choices populated dynamically on page 2 of the form. But when I try to access the selected value from the dropdown on the page 4 onwards of the form, I get blank value in rgpost for that field.

    However If I try to access the selected value of the dropdown on page 3 (next to the page where dropdown is) I can access the selected value using the rppost.

  20. SMD says:

    Hey thanks for this. I’m having a little issue. I created a custom functionality php file and loaded it into the plugins section of my wordpress. I started populating the php while using dreamweaver with the two separate sections of code above and upon adding the section section it keeps giving me a php errors with this line = “return $current_user->;__get($meta_key);” and its the semicolon in between the right angle bracket and the underline before get($meta_key). Anyone else having problems with this?

    Thanks

Leave a Reply