Last active
February 15, 2017 16:40
-
-
Save aldoreyes/9868621 to your computer and use it in GitHub Desktop.
Snippet to add attachments to a salesforce object that is created through the salesforce plugin for gravityforms by @katzwebservices
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_action("gform_after_submission", 'sf_add_attachments', 11, 2); | |
/** | |
* This will go through all your fileupload fields from the form, | |
* and it will create an attachment for each one of the that is not empty | |
* @param [type] $entry [description] | |
* @param [type] $form [description] | |
*/ | |
function sf_add_attachments($entry, $form){ | |
$parentID = gform_get_meta($entry['id'], 'salesforce_id'); | |
if($parentID){ | |
$base_dir = wp_upload_dir(); | |
$base_dir = $base_dir['basedir']; | |
$fields = GFCommon::get_fields_by_type($form, array("fileupload")); | |
$attachments = array(); | |
foreach ($fields as &$field) { | |
if(!empty($entry[$field['id']])){ | |
$filepath = $entry[$field['id']]; | |
$filepath = $base_dir.substr($filepath, strpos($filepath, 'uploads')+7); | |
$filename = pathinfo($filepath, PATHINFO_BASENAME); | |
$handle = fopen($filepath,'rb'); | |
$file_content = fread($handle, filesize($filepath)); | |
fclose($handle); | |
$encoded = chunk_split(base64_encode($file_content)); | |
$attachment_fields = array('Name' => $filename, | |
'ParentId' => $parentID); | |
$attachment_fields = array_map(array('GFSalesforce', '_convert_to_utf_8'), $attachment_fields); | |
$attachment_fields['body'] = $encoded; | |
$sObject = new stdClass(); | |
$sObject->type = 'Attachment'; | |
$sObject->fields = $attachment_fields; | |
$attachments[] = $sObject; | |
} | |
} | |
$api = GFSalesforce::get_api(); | |
$results = $api->create($attachments); | |
foreach ($results as $result) { | |
if($result->success){ | |
RGFormsModel::add_note($entry['id'], 0, __('Gravity Forms PoP Custom Integration'), sprintf('An attachment with Id #%s has been added on salesforce for this object', $result->id)); | |
}else{ | |
RGFormsModel::add_note($entry['id'], 0, __('Gravity Forms PoP Custom Integration'), sprintf('An error occurred Error: %s', $result->errors[0]->message)); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment