Last active
January 25, 2019 03:44
-
-
Save jkentjnr/64d87004b150f5a8c667 to your computer and use it in GitHub Desktop.
Blog - Loading Data into Salesforce from Google Sheets
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
// ----------------------------------------- | |
// CREATE CONTACTS FROM GOOGLE SHEET | |
// ----------------------------------------- | |
// Name of the entry in the Documents entity. | |
String dataFile = 'DemoExport'; | |
// ----------------------------------------- | |
// Get the URL from Documents and retrieve from Google Sheets as TSV. | |
Document d = [SELECT Id, Url FROM Document WHERE Name = :dataFile LIMIT 1]; | |
Http h = new Http(); | |
HttpRequest req = new HttpRequest(); | |
req.setEndpoint(d.Url); | |
req.setMethod('GET'); | |
HttpResponse res = h.send(req); | |
// Split the rows -- can have issues with Stack so be aware. | |
String[] rows = res.getBody().split('\n'); | |
// -------- | |
// Create a Unit of Work | |
fflib_ISObjectUnitOfWork uow = Application.UnitOfWork.newInstance(); | |
// This project has less than 200 contacts so get all existing contacts so | |
// we can either update or create new contacts later. | |
Map<String, Contact> contactMap = new Map<String, Contact>(); | |
List<Contact> contactList = [SELECT Id, Import_Key__c FROM Contact]; | |
for (Contact contact : contactList) { | |
if (contact.Import_Key__c != null) | |
contactMap.put(contact.Import_Key__c, contact); | |
} | |
for (Integer i = 1; i < rows.size(); i++) { | |
// Split the row into a column array. | |
String[] row = rows[i].split('\t'); | |
// Assign the columns to local variables | |
// TODO: Not validation to ensure rows have data - need to add. | |
String key = row[0]; | |
String name = row[1]; | |
String phone = row[2]; | |
String email = row[3]; | |
String line1 = row[4]; | |
String line2 = row[5]; | |
String city = row[6]; | |
String state = row[7]; | |
String postcode = row[8]; | |
// Determine if we have a new or existing contact. | |
Contact contact = (contactMap.containsKey(key) == false) | |
? new Contact() | |
: contactMap.get(key); | |
// Set the values. | |
contact.Import_Key__c = key; | |
contact.Name = name; | |
/* Omitted */ | |
// Add to unit of work as update or new. | |
if (contactMap.containsKey(key) == false) | |
uow.registerNew(contact); | |
else | |
uow.registerDirty(contact); | |
} | |
// Commit work. | |
uow.commitWork(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment