[SalesForce] MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa)

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.

public class ApplicationService
{
    public static void createContentWorkspaces(List<Application__c> records)
    {
        Set<String> names = new Set<String>();
        for (Application__c record : records)
            names.add(record.Account__c);
        createContentWorkspaces(names);
    }

    @future
    public static void createContentWorkspaces(Set<String> name)
    {
        List<ContentWorkspace> records = new List<ContentWorkspace>();
        for (String name : names) records.add(new ContentWorkspace(Name=name));
        insert records;
    }
}

See also: Mixed DML Operations in Test Methods.