You need to sign in to do that
Don't have an account?
waylonatcim
Creating folders using apex
I'm trying to figure out if a folder can be created using apex. The following code does not work:
Folder newFolder = new Folder(Name=folderName,Type='Document',AccessType='Public'); insert newFolder;
Apparently DML is not allowed on folders. Any thoughts on this?
Thanks!
Hey
I've had this issue before and have seen it in the forums.. I think that DML simply isn't allowed. The only way I've managed to work with it is to create the Folder in my Dev Org and the new folder into my local (Eclipse) code base. Dynamic folder creation doesn't seem possible:(
Cheers,
Wes
You cannot create folders via apex. You have to create it in SFDC via setup , and query that in apex for id.
You can't do it in a unit test either. And unless you use SeeAllData, you cannot query for folders either.
Please vote for this idea:
http://success.salesforce.com/ideaView?id=08730000000IqJuAAK
metadata api converted to apex class
you will use metadata api. It's a only option to create folder in apex code.
if you have any question about it. I will help you.
by
Ramakrishnan Ayyanar
+919944112175
softramki@gmail.com
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);
}
private MetadataService.ReportFolder createReportFolder( String folderName ) {
MetadataService.ReportFolder reportFolder = new MetadataService.ReportFolder();
reportFolder.fullName = //as per your requirement
reportFolder.name = //as per your requirement
return reportFolder;
}
Hope this helps.