Inside a computer

Pre-populate Fields using Gravity Forms

| 47 Comments

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

Categories: Code & Snippets, Plugins | Permalink

What next?

Hire me

If you couldn't quite manage this yourself, find it too intimidating, or just don't have the time to do it, you can always hire Dave to do it. Please get in touch so that we can discuss your needs.

Leave a comment

If you have a question, update, or comment about the tutorial, please leave a comment. I try and respond to every comment, though it may take a few days, so please check back soon.

Let a WordPress Expert help you

Do you want to try this, but feel like you need a helping hand, in case something goes wrong? My service, The WP Butler, gives you access to WordPress expertise whenever you need it. Better yet, I'll keep your site backed up, updated and secure, so that you don't have to worry about it. It's all part of the service. Use coupon DIWW and save 15% on all plans.

Visit The WP Butler

Author:

Dave has been tinkering with WordPress for many years, and he now shares his WordPress knowledge here on Do It WIth WordPress to help others realise its impressive power. He can also be hired to help with your WordPress needs. Dave, who is British, is married to his best friend, Marti, with whom he has a beautiful daughter, Ellie. When he's not dabbling with WordPress, he's probably eating Triscuits or hummus, watching an indie film or British TV show, spending time with friends or family, or exploring the world.

47 Comments

  1. 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.

    • 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.

    • 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.

      • 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!

        • 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. 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.

  3. 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!

    • 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. After some Googling i came to this post http://zzlatev.com/gravity-forms-upload-limits/
    Maybe could be the solution?

  5. 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

    • 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. 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,

    • 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. 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

  8. 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

    • 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. 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).

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

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

        • 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.

      • 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.

        • 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.

          • 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.

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

        • 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

  10. 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. 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

  12. 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?

  13. 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?

    • 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. 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. But I think that @Brad Trivers have already responded , I will take a look at his code tomorrow

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

  17. `//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.

    • 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. 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. 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.

Leave a Reply