I have created a basic trigger and want to insert a content library whenever an application is created but am receiving this error:
Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger GenerateLibraryTrigger caused an unexpected exception, contact your administrator: GenerateLibraryTrigger: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): ContentWorkspace, original object: Application__c: []: Trigger.GenerateLibraryTrigger: line 9, column 1
Code:
trigger GenerateLibraryTrigger on Application__c (after insert) {
ContentWorkspace lib = new ContentWorkspace();
for(Application__c a: trigger.new){
lib.name=a.Account__c;
insert lib;
System.debug('lib' + lib); } }
Best Answer
You are going to have to move your logic to a future method to create a separate transaction. To do so, you will need to move this logic to a separate class (which you should be doing anyway). Note that you also should not be calling any DML, futures, etc within a for loop. This is bulkification 101. Create a collection of names, then pass them in once your loop is done.
See also: Mixed DML Operations in Test Methods.