You need to sign in to do that
Don't have an account?
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: trigger.new){
uId.add(e.MID__c);
}
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()){
umap2.put(u.Emp_ID__c,u.Id);
}
for(CustomObject__c e: trigger.new){
if(umap2.containsKey(e.MID__c)){
e.User__c = umap2.get(e.MID__c);
}
else
{
clist.add(e);
}
}
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>();
for(CustomObject__ce:clist){
mid_cid.put(e.mid__c,e.Cost_Center__c);
mid_obj.put(e.mid__c,e);
}
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){
cid_account.put(acc.Cost_Center__c,acc);
}
for(CustomObject__c e:clist){
String emailAddr =e.Email_Address__c;
User u = new User(FirstName=e.First_Name__c,
LastName=e.Last_Name__c,
Alias=e.First_Name__c.substring(0,1)+e.Last_Name__c.substring(0,3),
email= e.Email_Address__c,
UserName=e.Email_Address__c,
CommunityNickname= emailAddr.split('@')[0],
ProfileId='00eQ0000000M59D',
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,
languagelocalekey='en_US',
localesidkey='en_US',
timezonesidkey='America/New_York',
emailencodingkey='UTF-8',
Emp_ID__c= e.MID__c);
newUserList.add(u);
}
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
Hi,
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.
Thanks,
Anoop Asok