You need to sign in to do that
Don't have an account?
Trigger in User object
Hi Team,
I have an issue while updating the User record.
Scenario: When a new User is created or updated with ProfileId =00eE0000000MyhV then a new record should be created in Custom__c object with User__c(Lookup)= New/Updated user id.
Condition: No duplicate User records should be created in Custom__c object.
The below trigger works when a new User is created but when a user is updated with new Profile (00eE0000000MyhV), I get this error message:
Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger CreateNewCustomRecord caused an unexpected exception, contact your administrator: CreateNewCustomRecord: execution of BeforeUpdate 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): Custom__c, original object: User: []: Trigger.CreateNewCustomRecord: line 12, column 1
trigger CreateNewCustomRecord on User (After insert, After update) {
for(User us : Trigger.new)
{
if(us.IsActive==TRUE && us.profileId == '00eE0000000MyhV')
{
List<Custom__c> CountRec=[Select id from Custom__c where User__c=:us.id ];
if(CountRec.size() <1)
{
try
{
Custom__c CreateRec=new Custom__c(Name=''Test Record,User__c=us.id );
insert CreateRec;
}
catch(Exception ex)
{
throw ex;
}
}
}
}
}
Thanks,
Madhan Raja M
Mixed DML exception can be easily avoided by making a future call.
Annote your method with @future annottaion .
You are trying to insert non set up object and set up object in a single context and this is well known exception.
Our Techie champion @Abhinav Gupta blogged on this topic and its intresting .The link i have provided below
Avoiding Mixed DML exception
Use @future Call for user update and this will solve your issue .Note you have limit of 200 per licence for future calls.But i guess in your case you should be fine
All Answers
Mixed DML exception can be easily avoided by making a future call.
Annote your method with @future annottaion .
You are trying to insert non set up object and set up object in a single context and this is well known exception.
Our Techie champion @Abhinav Gupta blogged on this topic and its intresting .The link i have provided below
Avoiding Mixed DML exception
Use @future Call for user update and this will solve your issue .Note you have limit of 200 per licence for future calls.But i guess in your case you should be fine
Thanks Mohit!