9

I'm writing a Trigger that After Insert of a new User, I need to create a Contact with that same new User information. I'm getting this error:

MIXED_DML_OPERATION

DML operation on setup object is not permitted after you have updated a non-setup object.

Can someone explain how I could work around this error? Thanks!

trigger UserInsertContactInsert1 on User (after insert) {

    if(Trigger.isAfter && Trigger.isInsert){
        Set<ID> usrIds = new Set<ID>();

        for(User u : Trigger.new){
            usrIds.add(u.id);
        }

        List<User> usrList = [SELECT Id, FirstName, LastName, Email, Phone FROM User WHERE Id IN :usrIds];
        List<Contact> cList = new List<Contact>();

        for(User u : usrList){
            cList.add(new Contact(FirstName=u.FirstName, LastName=u.LastName, Email=u.Email, Phone=u.Phone, OwnerID=u.ID, Related_User__c=u.Id));
        }

        insert cList;

    }
}
0

2 Answers 2

18

You should use @future class to avoid this error, as described in the Apex Developer Guide.

1
  • 2
    Thank you! That was exactly what I needed! I don't have enough reputation points to up-vote this, but I would if I could.
    – Stephen
    Apr 17, 2015 at 12:48
5

We cannot perform DML Operation on both Setup and Non-setup object in a same context of execution. The trigger is firing because of DML on User object, and you are trying to insert Contact record in the same context. That's why you are getting this error.

If you remove insert statement for contact record, then it will work fine. Although if you need to perform DML on contact as well, then use @Future annotation.

Not the answer you're looking for? Browse other questions tagged .