I'm trying to write an Apex class that queries data from an sObject and then writes that data to a csv file that is downloaded locally so that it can be uploaded to a big object. I'm adapting the approach from code that I found in another post which generates a csv string and then write it to a file. There is a section of the code that creates a blob and assigns that to the body of an Attachment object and then assigns sample values to the attributes of Name and parentId.
I've looked into where the value for parentId comes from but I haven't been able to find a clear answer. There isn't an attribute by that name of the object being queried so I'm not sure where the value is supposed to come from. What value should be assigned to the parentId?
The code for class is below:
List<Org_Snapshot__c> queryResults = [select id,Organization_Name__c, name from Org_Snapshot__c limit 10];
//String tempQuery = reportObj.SOQL_Query__c.subString(0,reportObj.SOQL_Query__c.indexOfIgnoreCase('From'));
List<String> queryFields = /*list of fields used in query exmaple -*/ new List<String>{'id','name','Organization_Name__c'};
List<String> csvValues = new List<String>();
String csvFileString = '';
for(String fieldName : queryFields)
{
csvFileString = csvFileString + ',' + fieldName.replace(',','');
}
csvFileString = csvFileString.replaceFirst(',','') + '\n';
String fileRow = '';
String fieldValue = '';
for(SObject obj : queryResults) //**THIS FOR LOOP IS CONSUMING MORE SCIRPT STATMENTS, IS THERE ANY WAY TO OPTIMIZE THIS ?**
{
fileRow = '';
System.debug('===>' + obj);
for(String fieldName : queryFields)
{
fieldValue = '' + obj.get(fieldName);
fieldValue = fieldValue.replace(',','');
fileRow += ',' + fieldValue;
System.debug('fieldValue: ' + fieldValue);
csvValues.add(fileRow);
}
fileRow = fileRow.replaceFirst(',','');
csvFileString += fileRow + '\n';
//SObject a = c.getSObject('Account');// for parent objects fields like Account.Name
}
Blob csvBlob = Blob.valueOf(csvFileString);
Attachment AttachmentObj = new Attachment(Body = csvBlob,
Name = 'Test-' +System.now().format('yyyy-MMM-dd-hh-mm-ss') + '.csv',
parentId = 'some id');
System.debug('blob: '+ csvBlob);
/*insert AttachmentObj; */
return csvValues;