One of my current projects has me working with Rocketgenuis’ Gravity Forms. It’s a great drag-and-drop form builder plugin for WordPress, and it’s quite extensible. I’m sure it’s got tons of other features, but I had to figure out something specific using what Gravity Forms gave me.
The project I’m working on needed a little more than just data collection from a form. It requires me to send files uploaded via Gravity Forms to a third-party API. That’s where the gform_after_submission
hook comes in. Unfortunately, the entry
parameter passed through the hook gives us URLs instead of a path to the local file.1 On top of that, it turns out you can use the gform_upload_path
filter to alter the storage path for individual forms.
So What’s a Developer to Do?
I had to dig through the Gravity Forms code, but did I find a couple of useful functions for our purposes. The GFFormsModel
class has static methods get_upload_path
and get_upload_dir
, both of which take a form id and return the necessary URL or directory.
Tools in hand, we can do some basic string manipulation to get what we’re after.
<?php add_action( 'gform_after_submission_1', 'my_gform_after_submission_1', 10, 2 ); function my_gform_after_submission_1( $entry, $form ) { $form_id = $entry[ 'form_id' ]; $upload_path = GFFormsModel::get_upload_path( $form_id ); $upload_url = GFFormsModel::get_upload_url( $form_id ); $filename = str_replace( $upload_url, $upload_path, $entry[ '1' ] ); // Now we can manipulate the local file as needed // Move it, copy it, send it to another service } |
The above code makes a few assumptions about your form. The _1
added to the submission action hook is indicative of the id of the form. And the index ‘1’ in the $entry
array is indicative of the control id in the form. These are things that may vary with your individual form.
But now you’ve got access to the local file to manipulate as you see fit.
-
Yes, you can use
file_get_contents
on URLs, but why do that for anything on your local filesystem? ↩
I like that this can be done, but how would you go about renaming the file, or moving it to a sub-folder with a field as the folder name? Trying to get my head around it this morning, but thats not going to well, ha.
Once you have the filename, there are a number of PHP functions that handle file operations. You can start with
rename
andbasename
.As for creating the subfolder with a field name, I’m not entirely sure. I don’t remember exactly what the
$entry
parameter contains. It may have field names, it may not. I think I remember it having an instance of the form. But if you can pull the field name from there, you can build the “copy to” directory to pass intorename
. Otherwise, you may have to hardcode the new directory.Hi,
I try to get an answer on this one 🙂
You write that the file can be sent to another service. How can that be accomplished?
/Melker
Awesome post, thanks!