Mixed DML happens when you try to do DML on certain "setup" objects, like User, Group and Profile, when you have already done DML on non-setup objects. It's a security thing. The usual solution is to do the User update asynchronously - i.e. in an @future method in a helper class. The code below does this. Please check my logic -- I am deactivating Users when the Contact.IsActive__c field is "false", while you were doing it when Contact.IsActive__c is "true". I thought this might be a bug. Also, in the future, be careful not to do DML inside of a for-loop, as your trigger is doing. This is not best-practice and makes the trigger unable to process bulk updates.
trigger ActiveUser on Contact ( after update ) { ContractTriggerHelper.deactivateUsers_future( Trigger.newMap.keySet() ); } public class ContractTriggerHelper { @future public static void deactivateUsers_future( List<Id> contactIds ) { List<User> usersToUpdate = new List<User>(); for ( User user : [ SELECT Id, IsActive FROM User WHERE ( Contact.IsActive__c = false AND ContactId IN :contactIds AND IsActive = true ) ] ) { user.IsActive = false; usersToUpdate.add( user ); } update usersToUpdate; } }
No comments:
Post a Comment