+ Start a Discussion
NecroGigglesNecroGiggles 

Trigger on Opportunity to update User object

I need to make a trigger on the opportunity object that Adds +1 to a custom filed on the user object every time an opportunity that the user owns has the "Date qualified" filed changed from null to having a date. 

I tired making a workflow but the field update cant cross to the user object. And I am not sure were to start on this code any help would be great.
ManojjenaManojjena
Hi NecroGiggles,

You can not Do DML for both Setup and nonsetup object so you need to use @future annotation to overcome that.

Please try with below code .
//Trigger

trigger UserUpdateOnOpportunityUpdate on opportunity (before update ) {
   List<Id> ownerIdList=new List<Id>();
   for(Opportunity opp :Trigger.new){
     if(Trigger.oldMap.get(opp.Id).Date qualified ==null && opp.Date qualified != null){
       ownerIdList.add(opp.ownerId);
     }
   }
   UserOwnCountClass.increaseCount(ownerIdList);
}
//Handler class 
public class UserOwnCountClass{
  @future
  public static void increaseCount( List<id> ussrIdList){
     List<User> usrListToUpdate=new List<user>();
     For(User usr : [SELECT id,CountFieldApi FROM User WHERE id IN : ussrIdList]){
      usr.CountFieldApi=usr.CountFieldApi+1`;
      usrListToUpdate.add(usr);
     }
     try{
       update usrListToUpdate;
     }catch(DmlException de){
       System.debug(de);
     }
  }
}
Please replace the variable accordigly.