I'm trying to implement a lightning-component-based custom display of email templates and their folders in a form similar to lightning:tree (a tree view with collapsible levels).

There's a nested folders structure:

  • -> Folder level 1
  • --> Folder level 2
  • ---> Folder level 3 {

  • email template 1,

  • email template 2,

  • ... }

Every folder can contain another folder and/or Lightning Email Templates.

Now I want to query Email Templates with information in which folder it's stored.

This one is easy: [SELECT Id, Name, FolderId FROM EmailTempate... etc].

The problem is that I need to know not only the direct Folder Id/Name in which the template is stored, but also parent, grandparent and so on. Even if you start from [SELECT Id, Name FROM Folder... etc] you're not able to get parent Id.

Is there a way to achieve it?

Mateusz :)

1 Answer 1


Actually, you can get parentId of the Folder just like this: SELECT ParentId FROM Folder

Here is the code you need to execute to retrieve all folders where email templates are stored:

List<EmailTemplate> templates = [SELECT Id, Name, FolderId FROM EmailTemplate];
Set<Id> foldersIdsToCheck = new Set<Id>();
for (EmailTemplate template_i : templates) {

Set<Id> foundFoldersIds = new Set<Id>();
List<Folder> foundFolders = new List<Folder>();

while (foldersIdsToCheck.size() > 0) { //retrieving parent folders until they exist
    List<Folder> folders = [SELECT Id, ParentId FROM Folder WHERE Id IN :foldersIdsToCheck];
    for (Folder folder_i : folders) {
        if (folder_i.ParentId != null) {

        if (!foundFoldersIds.contains(folder_i.Id)) {//store found folders to list to easily build tree when all are retrived

//TODO: build the tree with email templates and related folders

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .