Filtering WordPress Form Data with Gravity Forms

wordpress plugin gravity form, wordpress forms, gravity forms, wordpress plugins, webdevstudios, web development

WordPress filters are used to modify data before being rendered to the browser or saved to the database, and WordPress plugins typically provide filters to modify plugin behavior. Gravity forms is an extremely powerful form plugin that has many filters available. These filters can be used for validating form data, creating custom redirects, and even tying form data to other WordPress tables. The filter you hook into for validating submitted form data is the gform_validation filter.

An example of how to use a Gravity Forms filter is validating a birthdate against a minimum age requirement. To do this, you first need to loop through the $validation_result to get the form details before diving into the $_POST data.

add_filter( 'gform_validation', 'wds_validate_birthdate' );

function wds_validate_birthdate( $validation_result ) {
    $form = $validation_result['form'];
            
    $minimum_age = 18;
            
    // loop through form fields
    foreach( $form['fields'] as &$field ) {

        // do we have a date field with “birth” in the label
        if( 
            stristr( $field['label'], 'birth' ) 
            && ( 'date' == $field['type'] ) 
        ) {
            // check to make sure $_POST data is available for the field
            if( isset( $_POST['input_' . $field['id']] ) ) {
                
                // if this is an array, we’re using dropdowns for the date
                if( is_array( $_POST['input_'.$field['id']] ) ) {
                    $birthArr = $_POST['input_'.$field['id']];
                    
                    // did they fill in the birthdate?        
                    if( '' == $birthArr[0] ) {
                        $validation_result['is_valid'] = false;
                        $field['failed_validation'] = true;
                        $field['validation_message'] = 'Your birthdate is required!';
                    }
        
                    // Format date - month/day/year
                    $birthdate = $birthArr[0] . '/'. $birthArr[1] . '/' . $birthArr[2];
                } else {
                    $birthdate = $_POST['input_'.$field['id']];
                            
                    // Fail validation when datepicker field is null
                    if( '' == $birthdate ) {
                        $validation_result['is_valid'] = false;
                        $field['failed_validation'] = true;
                        $field['validation_message'] = 'Your birthdate is required!';
                    }
                }
                
                // Were they born in the future?
                if(
                    empty( $field['validation_message'] )
                    && strtotime( $birthdate ) > strtotime( 'now' )
                ) {
                    $validation_result['is_valid'] = false;
                    $field['failed_validation'] = true;
                    $field['validation_message'] = 'Hello time traveler!';
                }
                
                //  Check against the minimum age requirement
                if( 
                    empty( $field['validation_message'] )
                    && ! wds_check_minimum_age( $birthdate, $minimum_age ) 
                ) {
                    $validation_result['is_valid'] = false;
                    $field['failed_validation'] = true;
                    $field['validation_message'] = "You must be {$minimum_age} years or older!";
                }
        
            }
        }
    }
            
    $validation_result['form'] = $form;
    return $validation_result;
}

function wds_check_minimum_age( $birthdate, $minimum_age = 18 ) {
    $age = DateTime::createFromFormat( 'm/d/Y', $birthdate )->diff( new DateTime( 'now' ) )->y;

    if ( $age >= $minimum_age ) {
        return true;
    } else {
        return false;
    }
}

In the above example, we looped through the form fields and check to see if the field’s label contains ‘birth’ and has a type of date. Once we found the correct label and type, we searched for the submitted value in $_POST using the field’s ID. Once we had the submitted value, we had to determine which type was submitted so we could put it in the correct format before making sure the date wasn’t before today’s date and validating the date against the minimum age requirement.

Screen Shot 2015-02-26 at 12.11.13 PM

Another example of using a Gravity Forms filter: Let’s say your user creating a bundle of articles, and you want to save the lead ID from the form to a separate table. The reason you might want to do this could be that your client wants you to run a report that shows what was submitted via form, and what was created when saving the user’s bundle to a separate table. For this, you would use the gform_confirmation filter.

// GF confirmation
add_filter( 'gform_confirmation', 'wds_custom_gform_confirmation', 10, 4 );

function wds_custom_gform_confirmation( $confirmation, $form, $lead, $ajax ) {
    global $post, $wpdb;
    
    if( isset( $_GET['bundle_id'] ) ) {

        // update the bundle data with the lead id
        $query = $wpdb->prepare(
            "
            UPDATE {$wpdb->prefix}user_bundles
            SET lead_id = %d
            WHERE bundle_id = %d
            ", $lead['id'], $_GET['bundle_id'] );
                                
        // Do the query and check for errors
        if ( false === $wpdb->query( $query ) ) {
            if( $wp_error ) {
                return new WP_Error( 'db_query_error', 
                    __( 'Could not execute query' ), $wpdb->last_error );
            }
        }
        
        // Redirect to confirmation page
        wp_redirect( '/bundle-confirmation-page/?bundle_id=' . $_GET['bundle_id']);

    }

    return $confirmation;
}

In the above example, we are hooking into the filter that runs after the form has already submitted successfully. We first check to make sure the page has a bundle_id query parameter, then update the database table to also include the lead id from the “rg_lead_detail” table, and lastly we did a custom redirect to a confirmation page. Querying the data is as simple as joining two tables and looping through the results to index by either bundle_id or lead_id.

Screen Shot 2015-02-26 at 12.26.49 PM

Gravity forms is a valuable asset to any WordPress site and has a lot of awesome hooks to make life easier. These filters can be used to manipulate how a form is displayed, register additional scripts, modify field error messages, pass data to third-party applications, and many other things.

How do you use Gravity forms?

Using Vagrant and IIS for WordPress Development

vagrant+iis+wordpress

…And lo! It came to pass that I needed to set up a local environment built on IIS.

Many things (like communicating with a MS SQL server) can be emulated or replicated on a *nix environment, in which case the Vagrant workflow I’ve spent a lot of time and energy switching over to would work fine. In this case, however, I needed the environment to be specifically Windows-based, because the plugin I was planning on building was going to make use of COM functions to pull in and execute Visual Basic scripts that just wouldn’t run on anything other than Windows.

First, I asked my fellow devs. We do a lot of Microsoft work; maybe someone had a recipe or a Vagrant box I could use. No dice.

Vagrant is great because you can have different boxes emulating different environments. Your local machine’s filesystem (the “host” environment) can interact natively with the emulated operating system (the “guest” environment). My goal was to stick with Vagrant, somehow, to allow changes I make on my host to be reflected on the guest and then be able to see those changes in a browser. When no response was forthcoming, I took to Google. Surely someone has tried building on a virtualized Windows machine using Vagrant on OSX. Surely.

When I couldn’t find any answers on Google, I tried cobbling together what I could to build my own. What follows is how I have my local IIS Vagrant WordPress machine working. Your mileage may vary. It is, by no means, the best solution, and if you know of ways to improve the setup–particularly in syncing files between the two different filesystems–I’d be interested to hear them in the comments. At any rate, this method and this box works for me and I’m actively using it as a development environment.

Continue Reading

WDS Github Releases for February 2015

WebDevStudios releases, WebDevStudios, WordPress, github releases, best github releases, web development, find a web developer

Every month, WDS releases a bunch of goodies over on Github (and occasionally WordPress.org and elsewhere). While we typically share the links on our social media, we know that it’s easy for things to get lost in the noise, so we will be bringing you our top five(-ish) releases of every month from now on. While the vast majority are on Github (and for this month, they ALL are), we’ll sometimes also be featuring non-Github releases as well.

February was a busy month! We had a lot going on, and released some really exciting stuff!

Here are the top five releases from WebDevStudios:

Continue Reading

Team WDS Takes On Prestige Conference 2015

prestige conference, webdevstudios, brad williams, dre armeda, lisa sabin-wilson, tech conferences, business development conferences

Prestige Conference is coming up on February 27th-28th (next week!) in Las Vegas, and yes, WDS will be there!

Like PressNomics, Prestige is a tech conference that focuses on business and career development, rather than tech itself; most of the presentations are focused on discussing how to run a business in the tech industry, rather than on improving technical skills.

One of the biggest benefits of conferences like this is, of course, the presentations from well-established professionals who know their stuff, but also, the conversations that happen in between the formal scheduling–the hallway chats, brainstorming over meals, and networking amongst other like-minded pros in the industry.

A few major WDS movers and shakers are going to be in attendance: Brad will be speaking, and Lisa and Dre will be there too, making friends (as per usual!).

Hiring Employee Number One: From Freelancer to Agency – February 28th, 1 PM

Brad Williams will be discussing the process of hiring employee number one based on his experience building and growing WebDevStudios. His presentation will cover how the company grew to the point where hiring additional employees was necessary, as well as what he learned along the way. The process was hardly seamless, and he will discuss lessons learned from mistakes made, as well as tips on how to do it right.

As per usual, we want to highlight a few other presentations that caught our eye:

Continue Reading

10 Things I Learned Migrating Websites to WordPress

migrating websites to wordpress, webdevstudios, wordpress help, how to use WordPress, web development

Since joining WDS, I’ve had the awesome opportunity to be a part of our internal migrations team and create scripts to help migrate sites for Microsoft to WordPress. It’s an ongoing joke about my joy for migrations because in my initial interview I expressed that I wasn’t too fond of them and plugins were my thing. Boy, was I in for a surprise, because I’ve been studying and writing migrations scripts for almost a year now.

This post is born out of a year of challenges, growth, and my new found love and respect for the beast known as WordPress Migrations. Its purpose is to help those who may be entering this space for the first time or needing to refine their processes become more efficient (and make some more money) doing migrations.

This is not an exhaustive list, but here are ten things that I learned migrating websites to WordPress:

Continue Reading

Tech Non-Profit Spotlight: Hack the Hood

hack the hood, webdevstudios, tech non-profits, technology non-profits, oakland non-profits

Prior to becoming a writer and communications dork, I was immersed in the non-profit world. From non-profits that focused on the arts to those that offered direct assistance to underserved communities, playing small time Wonder Woman (or trying, at least) was my life.

Although I’m no longer part of that world professionally, it’s still something I’m very passionate about, which is why WebDevStudios’  contribution to the community in both charitable and educational capacities appealed to me immediately. As giving back is part of the heart of WDS (and the big, squishy hearts of our wonderful team), it only made sense for us to turn the lens outward and shine a light on other people in the tech community who are passionate about the same.

As a result, this is the first of a monthly column focusing on different organizations who are doing the good work–the meaty, meaningful stuff–and making the world a better place.

Continue Reading

Using Git Flow and Forget to Branch? Stash it.

git-workflow

Here at WebDevStudios, we use a variation of the Git workflow known as Git Flow.

One of the benefits of using Git is quick and easy branching and merging without conflicts. Git Flow makes extensive use of branches to ensure that work that you are currently developing doesn’t break things that someone else is working on.

A lot has been written about Git Flow–the first time I learned about it was on Jeff Kreeftmeijer’s blog a couple years ago, but it was originally devised in 2010 by Vincent Dreissen. Since then, Git Flow has been added to popular Git GUI clients like SourceTree and Tower.

For those of you not familiar with Git Flow, I’m not going to go in depth about how it works, but I’ll walk through a really simple workflow example and how we use it at WDS.

Continue Reading

Lisa Sabin-Wilson Does the Design Bloggers Conference

design bloggers conference, webdevstudios, lisa sabin-wilson, wordpress for dummies, interior design, web development, looking for a web developer, looking for a web designer

As many of you already know, WDS folks are regulars at the tech events around the world–particularly when it comes to WordPress. We love teaching, we love learning, and we love meeting people in our community. Recently, though, Lisa received an invitation to something unexpected, and it was an opportunity that she couldn’t pass up.

Lisa was invited to speak at the Design Bloggers Conference later this month! Now, this isn’t a conference focusing on web design, but on interior design. It does seem a little outside of our purview, doesn’t it? Considering the new reports that WordPress is hosting almost a quarter of the sites worldwide, it may not be as surprising as you (and we) initially thought!

Continue Reading

Handling AJAX in WordPress in Style

handling-ajax-in-style
AJAX (Asynchronous Javascript and XML) isn’t something that should be feared by anyone. It’s insanely powerful, versatile, and can provide your users cool experiences like processing forms without page redirection, dynamically loading posts while a user scrolls the page, and much more. Most of all, WordPress has a few nifty gems up its sleeve.
In this post, I’ll show you how I handle AJAX in WordPress:

Continue Reading

How to Set Up HTTPS on WordPress Multisite Without Headaches

https715x242

Every couple months or so, Google seems to like to shake things up a bit and add some new criteria by which they rank sites. One of the most recent of these shakeups was that your site might now be ranked based on whether it supports https. This led to a massive freakout in which everyone and their mom tried to set up HTTPS on their site. Historically, getting HTTPS working isn’t as easy as all that and I’m sure many of you reading this post were either too intimidated by the process or started and then gave up.

Recently I got HTTPS working on my site(s), and I’m going to share with you how I got it working (for free).

Continue Reading