Gravity Forms is by far our favorite WordPress plugin around these parts. It’s incredibly versatile and functional and the hooks that are available are beyond useful. They have hooks for just about everything!
If you use the wrong hooks for a task however, it can be very tedious to create everything that you need to. For example, we will often use custom database tables for items that don’t quite fit into the WordPress post model so as to not bloat up the posts & postmeta tables – think site messages for example. However, we still use Gravity Forms to handle the heavy form creation work because, you know, it’s the best and coding forms is a terrible, terrible task.
The normal method for this involves using the gform_field_value hook – this way you can insert a value into the individual field with ease. However, what if you have 20 or 30 fields to fill in? It gets quite tedious:
Imagine that going on for quite a while. This breaks almost all the rules in all the wrong ways; there’s a lot of room for error, you’re constantly repeating yourself, and you have to modify it every time you make a change to your data or your form. It’s way too much code for very little reason.
Enter gform_pre_render – this handy little hook is most often used for tasks such as creating a list of options for a select element or other tasks that need to be completed before the form is actually rendered to the user. We can use it for our advantage however.
As you can, this function will cut a LOT of time off of your development time and we cut our total code from over 200 lines to less than 70! There’s a couple of assumptions that are important to note here:
- You need to use a constant naming pattern in your dynamic population in Gravity Forms. Here, we’re using “contact_”[field_name] and [field_name] always matches what’s in our database.
- We’re using a GET variable to fill in the ID for our query – you can use whatever you like, but just change out the GET check at the beginning
- I’m using $wpdb->query to return an array with ARRAY_A set – you need to use ARRAY_A. If you don’t have a database query, just be careful with your array naming