function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

Help please on trigger

trigger UpdateUser on CustomObject__c(before insert) {
 list<CustomObject__c> clist = new list<CustomObject__c>();
 String[]uId = new String[]{};
 for(CustomObject__c e:{
 map<Id,User> umap  = new map<Id,User>([Select u.Emp_ID__c, u.Id From User u where u.Emp_ID__c in:uId]);
 map<String,Id> umap2 = new map<String,Id>();
 for(User u:umap.values()){
  for(CustomObject__c e:{
          e.User__c = umap2.get(e.MID__c);
 Map<String, String> mid_cid = new Map<String, String>();
 Map<String, CustomObject__c> mid_obj = new Map<String, CustomObject__c>();
 Map<String, Account> cid_account = new Map<String, Account>();
 List<User> newUserList = new List<User>();

  List<Account> alist = [Select a.Role_ID__c, a.Name, a.Id, a.Cost_Center__c From Account a where a.Cost_Center__c in : mid_cid.values()];

  for(Account acc:alist){

  for(CustomObject__c e:clist){
      String emailAddr =e.Email_Address__c;
      User u = new User(FirstName=e.First_Name__c,
                        email= e.Email_Address__c,
                        CommunityNickname= emailAddr.split('@')[0],
                       UserRoleId = cid_account.get(e.Cost_Center__c).Role_ID__c, // if i comment this line then its working
                       Branch__c = cid_account.get(e.Cost_Center__c).Name,
                     Emp_ID__c= e.MID__c);
  insert newUserList;



when iam trying to create new custom object record.iam getting following error.


 Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger UpdateUser caused an unexpected exception, contact your administrator: UpdateUser: execution of BeforeInsert 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): User, original object:  CustomObject__c: []: Trigger.UpdateUser: line 70, column 1

Anoop AsokAnoop Asok


You cannot update the user record with UserRoleId populated in the before insert context, this is a Salesforce restriction. Please refer to the section sObjects That Cannot Be Used Together in DML Operations in Apex Developer Guide.


The solution for this is to put the user insert/update logic to an asynchronous method and invoke it from the trigger. You can refer to the Future Annotation section in the developer guide.



Anoop Asok