Use Case : Get the Contract object Field Label and Field Name (API) name & Export that result to CSV file and Send Email Notification.
//To get all the objects details
Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
Map<String, Schema.SObjectField> fieldMap = schemaMap.get('Contract').getDescribe().fields.getMap();
string header = 'FIELD LABEL , FIELD NAME\n'; //CSV Header Row
string contrExcelStr = header ;
//Loop through the field map and get the object field label & field name(API Name)
for(Schema.SObjectField sfield : fieldMap.Values())
{
schema.describefieldresult descField = sfield.getDescribe();
mapResult.put(descField.getLabel(),descField.getname());
string recordString = descField.getLabel() +','+descField.getname() +'\n';
contrExcelStr = contrExcelStr +recordString;
}
//Email Notification
Messaging.EmailFileAttachment contrCsvAttch = new Messaging.EmailFileAttachment();
blob csvBlob = Blob.valueOf(contrExcelStr);
string csvname= 'Contract.csv';
contrCsvAttch.setFileName(csvname);
contrCsvAttch.setBody(csvBlob);
Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
String[] toAddresses = new list<string> {'test@gmail.com'};
String subject ='Contract CSV';
email.setSubject(subject);
email.setToAddresses( toAddresses );
email.setPlainTextBody('Contract CSV ');
email.setFileAttachments(new Messaging.EmailFileAttachment[]{contrCsvAttch});
Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
//Sent Email
Very Nice Post! Thank you so much for sharing this informative post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
ReplyDeleteSaleforce Developer Training in Electronic City
Thanks Deepika!! great code!! I only miss the definitio of
ReplyDeleteMap mapResult = new Map();
Thanks a lot! best regards, Jose Fluxa
This comment has been removed by the author.
ReplyDeleteGreat article..
ReplyDeleteIf instead of metadata, if i want fields as col name and data as records. How would be manipulate this existing code? Thank you
hi, i want to download one [articular record through a Download button on record details page. can you help me how to achive this
ReplyDeleteHi Deepika,
ReplyDeleteI'm also working on the same requirement and thanks to your blog that I have found the solution but as I'm new to salesforce, so can please help me how to execute it in anonymous window.
That will be highly appreciated.