Thursday 21 November 2013

How to Avoid MIXED DML Operation in Salesforce

Problem:

Updating Custom Setting values after user record is created or updated

Custom Setting API Name : ActiveUser__c
Field Name : Name(Standard Field) - It contains profile name
ActiveUsers__c: This field will be updated.

I have add once custom setting value,It contains
Name: Customer Portal Manager Custom(Profile Name)

Whenever creating or updating user from above mentioned Profile with the Status Active or Inactive. ActiveUsers__c is the Field will be updated.

You can add multiple profile name in custom setting.

Solution:

To avoid mixed dml operation you need to insert record with @future annotation.

Apex Trigger:

  1. trigger usertoActive on User (after insert, after update)
  2. {
  3.     Set<Id> usrID=new Set<Id>();
  4.     Set<Id> ProID=new Set<Id>();
  5.    
  6.     for(User ur:Trigger.new)
  7.     {
  8.         usrID.add(ur.Id);
  9.         ProID.add(ur.ProfileId);
  10.     }
  11.     activeUser.userAdd(usrID,ProID);
  12. }


Apex Class:

  1. global class activeUser
  2. {  
  3.     @future  
  4.     public static void userAdd(Set<Id> userIds,Set<Id> prid)
  5.     {
  6.         Profile pro=[select Name from Profile where Id=:prid];
  7.         List<User> user = [select Id, IsActive from user where Id in:userIds and Profile.Name=:pro.Name];
  8.         List<ActiveUser__c> licenseUpdate=[select ActiveUsers__c  from ActiveUser__c where Name=:pro.Name];
  9.        
  10.         for (ActiveUser__c au: licenseUpdate)
  11.         {
  12.             for(User ur:user)
  13.             {
  14.                 if(ur.IsActive)
  15.                 {
  16.                     au.ActiveUsers__c=au.ActiveUsers__c+1;
  17.                 }
  18.                 else
  19.                 {
  20.                     au.ActiveUsers__c=au.ActiveUsers__c-1;
  21.                 }
  22.                
  23.             }
  24.         }
  25.        
  26.         update licenseUpdate;
  27.        
  28.     }
  29. }

Reference: Mixed DML

No comments:

Post a Comment

Activities: Assign Tasks to a Queue Salesforce Lightning

Salesforce announced to assign Tasks to a Queue beginning from Spring'20 release. How does it work? In Setup, enter Queues in th...