[SalesForce] Create a queue with a trigger from a custom object

I'm trying to do a trigger to create a queue from a custom object and I'm get this error:

Review all error messages below to correct your data. Apex trigger
ProjectHandler caused an unexpected exception, contact your
administrator: ProjectHandler: 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):
QueueSobject, original object: Project__c: []: Trigger.ProjectHandler:
line 8, column 1

Where is the code:

trigger ProjectHandler on Project__c (after insert) {
    for (Project__c project : Trigger.new) {
        String queueName = project.Name;
        Group queue = new Group(Name=queueName, Type='Queue',DoesSendEmailToMembers=true);
        insert queue;

        QueuesObject qso = new QueueSObject(QueueID = queue.id, SobjectType = 'User_in_Project__c');
        insert qso;

    }
}

There is any workaround? Two different triggers donĀ“t solve the problem either. I can not create a trigger on a QueueSObject too.

Best Answer

One workaround would be to use future methods to create the setup objects. Have a look at this post for more details on how to do it.

You also need to bulkify your code so that you don't have the inserts within a for loop.