February 22nd, 2014: Gravity Forms now supports conditional logic rules comparing against empty values. Updated the article verbiage accordingly.
Have you ever wanted to conditionally show or hide a field depending on whether the user is logged in or not? No, never? How about if you only want to require a captcha field for non-logged-in users? Or how about if you’re running a listings site (powered by Gravity Forms, of course). Anyone can submit a listing but you want to limit the ability to upload an image with the listing to registered users. Didn’t think about that, huh!?
Now that we’re agreed that this could, indeed, be useful, let’s dig in!
Step 1: Create a Hidden Field to Store the User Login
We don’t want to do any more work than we have to so we’re going to let Gravity Forms do most of the work for us. Let’s kick things off by creating a new Hidden field.
Nothing special here. Make sure you give your Hidden field an obvious label so you won’t forget the purpose of this field in the future. I like to append “(hidden)” to my Hidden fields so anywhere this field label is referenced I know it is a hidden field. Personal preference.
There isn’t a whole lot happening on the advanced field settings either… just a small bit of clever wizard magic. For the “Default Value” setting, we’re using a Gravity Form merge tag to populate the logged in user’s login name. The “Default Value” setting should look like this:
If the user isn’t logged in, the user login merge tag won’t populate anything and the value of this field will be empty. Now we’re ready to apply some conditional logic based on our newly created Hidden field.
Step 2: Apply Conditional Logic to Other Fields Based on the User Login Hidden Field
Open up the advanced field settings for whichever field you want to conditionally show or hide if the user is not logged in. At the very bottom of the advanced tab you’ll find Gravity Forms’ default conditional logic.
In our case, we want to compare the value of the user login hidden field we created in Step 1 to an empty value (see example below).
If the user is not logged in, our hidden field will be empty but if the user is logged in, it will be populated with the username. This allows us to create conditional logic based on whether the User Login Hidden field is empty or not. If it is, the user is not logged in; otherwise, the user is logged in.
In plain English, this conditional logic would read: “Show this field if the user login hidden field is not empty (aka, the user is logged in)”. This means only logged-in users would be able to see this field.
Simple enough, eh? You can use this same concept in all sorts of other wizardly ways! Let us know if you use this setup and how it’s works for you. Comments are magical.