Gravity Wiz // Gravity Forms // Field-specific Upload Path
<?php
/**
* Gravity Wiz // Gravity Forms // Field-specific Upload Path
*
* Provides a method for specifying field-specific file upload paths.
*
* @version 1.0
* @author David Smith <david@gravitywiz.com>
* @license GPL-2.0+
* @link http://gravitywiz.com/...
*/
class GF_Field_Specific_File_Upload_Path {
var $current_field = null;
function __construct() {
add_filter( 'gform_save_field_value', array( $this, 'stash_current_field_id' ), 10, 4 );
add_filter( 'gform_upload_path', array( $this, 'modify_upload_path' ) );
}
/**
* This is a little tricky... we get the $field that is about to be saved, but the field we want is whatever is next in the queue.
* To do this, we'll simply search for the next file upload field based on the position of the current field.
*/
function stash_current_field_id( $value, $entry, $current_field, $form ) {
$is_next = false;
$next_field = false;
foreach( $form['fields'] as $field ) {
$is_file_upload = GFFormsModel::get_input_type( $field ) == 'fileupload';
$is_current_field = $field['id'] == $current_field['id'];
if( $is_next && $is_file_upload ) {
$next_field = $field;
break;
} else if( $is_current_field ) {
$is_next = true;
}
}
$this->current_field = $next_field;
return $value;
}
function modify_upload_path( $upload_path ) {
// modify the upload path based on the current field ID:
// $current_field_id = $this->current_field_id
$applicable_forms_fields = array(
array(
'form_id' => 13,
'folder_name' => rgpost( 'input_4' ),
'field_ids' => array( 6, 15, 16 )
),
array(
'form_id' => 547,
'folder_name' => rgpost( 'input_1' ),
'field_ids' => array( 2 )
),
array(
'form_id' => 547,
'folder_name' => rgpost( 'input_4' ),
'field_ids' => array( 3 )
)
);
foreach( $applicable_forms_fields as $forms_fields ) {
$is_current_form = $this->current_field['formId'] == $forms_fields['form_id'];
$has_current_field = in_array( $this->current_field['id'], $forms_fields['field_ids'] );
if( $is_current_form && $has_current_field ) {
$applicable_fields = $forms_fields['field_ids'];
$folder_name = $forms_fields['folder_name'];
}
}
if( ! isset( $applicable_fields ) || ! isset( $folder_name ) ) {
return $upload_path;
}
$upload_path['path'] = "/Applications/MAMP/htdocs/localhost/wp-content/uploads/{$folder_name}/";
$upload_path['url'] = "http://localhost/wp-content/uploads/{$folder_name}/";
return $upload_path;
}
}
new GF_Field_Specific_File_Upload_Path();