Wednesday 13 August 2014

Folder Creation using Apex Code in Salesforce


Some the requirements may come like the below,
     
           Client need to create Email template folder through visualforce page. Consider you have a custom Visualforce page and one input text box and save button. When user give the name of email template folder in vf then save it means the Email template folder need to be created.
Here is the base code to create an email template folder,
  1. HTTP h = new HTTP();
  2. HTTPRequest req = new HTTPRequest();
  3. req.setMethod('POST');
  4. req.setHeader('Content-Type''text/xml');
  5. req.setHeader('SOAPAction''create');
  6.  
  7. String b = '<?xml version="1.0" encoding="UTF-8"?>';
  8. += '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
  9. += '<soapenv:Header>';
  10. += '<ns1:SessionHeader soapenv:mustUnderstand="0" xmlns:ns1="http://soap.sforce.com/2006/04/metadata">';
  11. += '<ns1:sessionId>' + UserInfo.getSessionId() + '</ns1:sessionId>';
  12. += '</ns1:SessionHeader>';
  13. += '</soapenv:Header>';
  14. += '<soapenv:Body>';
  15. += '<create xmlns="http://soap.sforce.com/2006/04/metadata">';
  16. += '<metadata xsi:type="EmailTemplateFolder" xmlns="http://soap.sforce.com/2006/04/metadata">';
  17. += '<name>PersonalTemplates</name>'; //Email template Folder Label Name
  18. += '<fullName>PersonalTemplates</fullName>'; //Email template Folder API Name
  19. += '<accessType>Public</accessType>'; // Email Template Folder Visibility
  20. += '<publicFolderAccess>ReadWrite</publicFolderAccess>'; //Email Template Access Level
  21. += '</metadata>';
  22. += '</create>';
  23. += '</soapenv:Body>';
  24. += '</soapenv:Envelope>';
  25.  
  26. req.setBody(b);
  27. req.setCompressed(false);
  28. // Set this to org's endpoint and add it to the remote site settings.
  29. req.setEndpoint ('https://na15.salesforce.com/services/Soap/m/25.0'); // Change this domain based on your org. Like na17,ap1 something.
  30. HTTPResponse resp = h.send(req);
  31. System.debug(resp.getBody());

If you want to check this code working, Go to Developer console, click Execute Anonymous window (CTRL+E), Paste the above code and before execute this code Create remote site setting with your domain address mentioned in the above Code.

Finally click execute, the go to your email folder then you will see the folder called as “PersonalTemplates” in your org.

Change this base code according to your requirement...

Happy Coding…!

No comments:

Post a Comment

Activities: Assign Tasks to a Queue Salesforce Lightning

Salesforce announced to assign Tasks to a Queue beginning from Spring'20 release. How does it work? In Setup, enter Queues in th...