Last active
June 18, 2024 13:54
-
-
Save jongpie/6cef55323179bc71300efb3d94b48165 to your computer and use it in GitHub Desktop.
SFDX: Retrieve All EmailTemplates
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
// Get the email templates | |
Set<String> folderNames = new Set<String>(); | |
List<EmailTemplate> emailTemplates = [SELECT Id, DeveloperName, FolderName FROM EmailTemplate ORDER BY FolderName, DeveloperName]; | |
for (EmailTemplate emailTemplate : emailTemplates) { | |
folderNames.add(emailTemplate.FolderName); | |
} | |
// Get the folder dev names - this assumes the Folder.Name (display name) is unique in the org | |
Map<String, String> folderDisplayNameToDevName = new Map<String, String>(); | |
for (Folder folder : [SELECT Id, DeveloperName, Name FROM Folder WHERE Name IN :folderNames and Name != 'Unfiled Public Classic Email Templates']) { | |
folderDisplayNameToDevName.put(folder.Name, folder.DeveloperName); | |
} | |
// Build the final list of email templates | |
List<String> qualifiedMetadataNames = new List<String>(); | |
for (EmailTemplate emailTemplate : emailTemplates) { | |
if (folderDisplayNameToDevName.get(emailTemplate.FolderName) != null) { | |
String folderDevName = folderDisplayNameToDevName.get(emailTemplate.FolderName) + '/'; | |
qualifiedMetadataNames.add('EmailTemplate:' + folderDevName + emailTemplate.DeveloperName); | |
} | |
} | |
// Generate the sfdx commands | |
Integer powershellCommandLengthLimit = 7000; // Apparently, powershell can't run commands that are longer than 8,191 (using 7,000 for some buffer) | |
List<String> sfdxCommands = new List<String>(); | |
final String baseSFDXRetrieveCommand = 'sfdx force:source:retrieve --metadata '; | |
String currentSFDXRetrieveCommand = baseSFDXRetrieveCommand; | |
for (String qualifiedMetadataName : qualifiedMetadataNames) { | |
// If adding the report name would cause the string to exceed PowerShell's limit, then instead start a new string | |
if ( (currentSFDXRetrieveCommand + ',' + qualifiedMetadataName).length() >= powershellCommandLengthLimit) { | |
sfdxCommands.add(currentSFDXRetrieveCommand); | |
currentSFDXRetrieveCommand = baseSFDXRetrieveCommand; | |
} | |
String delimiter = currentSFDXRetrieveCommand == baseSFDXRetrieveCommand ? '' : ','; | |
currentSFDXRetrieveCommand += delimiter + qualifiedMetadataName; | |
} | |
sfdxCommands.add(currentSFDXRetrieveCommand); | |
// Finally, output the list of sfdx commands - these can then be copy/pasted into a terminal to run | |
String commandsSummaryInfo = 'Number of SFDX commands to run==' + sfdxCommands.size(); | |
System.debug('\n\n' + commandsSummaryInfo + '\n\n' + String.join(sfdxCommands, '\n\n') + '\n\n\n\n'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment