Our 3rd party application possesses a functionality to archive records by replacing the original entry with an Attachment containing a .csv file that includes all fields along with their respective values for a maximum of 150 records.
Regrettably, the application lacks a feature to restore records from the archive. To address this limitation, I am currently working on writing an Apex class to handle the restoration process. However, there is a challenge due to the inconsistent structure of the .csv file. The number of fields and their positions may vary, as any field not holding a value for any record will be omitted from the .csv.
My goal is to create an Apex class that can analyze the .csv header, identify the relevant updatable fields, and then insert the records accordingly.
Though I have managed to complete the initial part of the process, I’m encountering difficulty in finding a solution to dynamically match the field names in the header with the corresponding field values in the .csv lines.
For instance, in my debug, I can currently call out a specific column number (e.g., fieldValues[8]) and retrieve its value. However, my intention is to achieve this dynamically by using the field name obtained from the header.
Below is the code I have written so far:
(Unfortunately, since you haven’t provided the actual code, I’m unable to display your specific implementation. Please share your code, and I’ll be happy to help you with the dynamic field matching challenge.)
List<Attachment> attachments = [ SELECT Id, body FROM Attachment WHERE Parent.Name LIKE 'Archiving Outbound Interface Requests %' Limit 10 ]; list<OutboundInterfaceRequest__c> oirs_Insert = new list<OutboundInterfaceRequest__c>(); for(Attachment a : attachments){ String stringBody = a.body.tostring(); list<String> filelines = stringBody.split('\n'); System.debug('filelines=' + filelines.size()); Map<Integer, String> myMap; list<String> fieldNames = new list<String>(); fieldNames = filelines[0].split(','); OutboundInterfaceRequest__c oir = new OutboundInterfaceRequest__c(); Map<String, Schema.SObjectField> fieldMap = oir.getsObjectType().getDescribe().fields.getMap(); for (Integer i=1;i<filelines.size();i++){ list<String> fieldValues = new list<String>(); fieldValues = filelines[i].split(','); for(String fn : fieldNames){ if(fieldMap.containsKey(fn) && fieldMap.get(fn).getDescribe().isUpdateable()){ system.debug('fieldName = ' + fn + ', fieldValue = ' + fieldValues[8]); //oir.put(fn, sourceFields.get(fn)); } } } }