+ Start a Discussion
Ramakrishnan AyyanarRamakrishnan Ayyanar 

How to create folder using Apex code?

I tried to create folder via apex code
      
      code:

        Folder fold=new Folder();
        fold.AccessType='Shared';
        fold.DeveloperName=UserInfo.getUserName();
        fold.AccessType='Shared';
        fold.Name='testfolder';
        fold.Type='Report';
        insert fold;

i got the error dml not allowed on folder.



Satish_SFDCSatish_SFDC
You cannot create folder through Apex.

We can however create a folder manually and query it through apex.

Regards,
Satish Kumar
Satish_SFDCSatish_SFDC
Just found an Idea related to this.

https://success.salesforce.com/ideaView?id=08730000000IqJuAAK

Regards,
Satish Kumar
Ramakrishnan AyyanarRamakrishnan Ayyanar

@Satish_SFDC

It's possible create folder in apex code.

using metadata api converted to apex class.

I did that.

 

v jv j
hi Ramakrishnan,

can you share how you achived this through metadata API, waiting for reply.
Shaun RipleyShaun Ripley
Hey, for anyone that stumbles across this thread, you can also use the rest api to achieve the results.
In my particular use case, any time a user is created, we want a shared folder created for this person.

The code I have used for this situation is as folows (noting this is not set up for unit testing):

@Future(Callout=true)
public static void createUserFolder(String name)
{
    if ( Test.isRunningTest() || name == null || [SELECT Id FROM Folder WHERE Name = :name AND ParentId = :SHARED_FOLDER_ID].size() != 0 ) {
        return;
    }

    HttpRequest req = new HttpRequest();
    Http http = new Http();
    req.setMethod('POST');
    req.setEndpoint(Url.getSalesforceBaseUrl().toExternalForm() + '/services/data/v49.0/folders/');
    req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());
    req.setHeader('Content-Type', 'application/json');
    req.setBody(JSON.serialize(new Map<String, String>{
        'label' => name,
        'name' => name.toLowerCase().replaceAll('[^a-zA-Z]', '_') + '_generated',
        'type' => 'report',
        'parentId' => SHARED_FOLDER_ID
    }));
    http.send(req);
}