+ Start a Discussion
Claudia daCostaClaudia daCosta 

How to create a conditional autonumber?

I'm trying to generate a conditional autonumber based on a field value.  I'm trying to round robin leads based on field being changed to "Demo Scheduled". 

I'm looking for the code to use in building the trigger. Can anyone help me with that?

Any help would be great! I'm stuck.

Thanks.

Sanjay Bhati 95Sanjay Bhati 95
Hi Claudia daCosta,

Please have a look on the below code for Round Robin.
 
public static void channelPartnerRoundRobin(List<Lead> LeadList){
        List<Lead> leadToUpdate = new List<Lead>();
        Map<Id,Integer> userCountMap = new Map<Id,Integer>();
        List<leadWrapper> userCountList = new List<leadWrapper>();
       for(Lead le :LeadList){
            if(le.FieldValue == 'Demo Sheduled'){
                leadToUpdate.add(le);
            }
        }
        if(leadToUpdate.size() > 0){
            leadToUpdate = [Select Id,OwnerId,Owner.Email From Lead Where Id IN:leadToUpdate];
            
            for(AggregateResult ar : [Select count(Id) usrCnt,ownerId From Lead Where FieldValue ='Demo Scheduled' Group by OwnerId ]){
                userCountMap.put(String.valueOf(ar.get('ownerId')),Integer.valueOf(ar.get('usrCnt')));
                
                
            }
            for(id key : userCountMap.keyset()){
                leadWrapper lw = new leadWrapper(key,userCountMap.get(key));
                userCountList.add(lw);
            }
            for(Lead le : leadToUpdate){
               userCountList.sort();
               if(userCountList.size() > 0){
                   le.ownerId = userCountList[0].userId;
                   userCountList[0].count += 1;
               } 
            }
            if(leadToUpdate.size() > 0){
                if(trigger.isAfter){
                    update leadToUpdate;
                }
            }
        }
    }


public class leadWrapper implements Comparable {
        public string userId;
        public Integer count;
        
        public leadWrapper(String userId,Integer count){
            this.userId = userId;
            this.count = count;
        }
        public Integer compareTo(Object objToCompare) {
            return Integer.valueOf(count- (((leadWrapper)objToCompare).count));
        }
    }