+ Start a Discussion
gregusagregusa 

How do I match on a value contained in a list or set using Apex in a Trigger

 

I have a trigger that needs to filter only the records affected that fall into a certain Record Type.  In the past I've made multiple calls to get some variables for the record types I want to use and then use if statements, but that is a poor use of resources.  I'd rather just pull those record types into a list or set so that I could match for a value in a set when looping.

 

Here's what I'd like to do:

 

// Create a list of RecordTypes we want to check for
List<RecordType> rtID = [SELECT Id FROM RecordType WHERE (SobjectType = 'Opportunity') AND (Name = 'Annuity' OR Name = 'Life' OR Name='LTC' OR Name = 'TLC')]; // Create a list for Opportunities that match our RecordType criteria List<Opportunity> opptsToWorkOn = new List<Opportunity>(); // Loop through the Opportunities being updated or deleted and see if there are any // for the record types we want. if(trigger.isDelete){ for (Opportunity o : Trigger.old) {

\\ #### HERE IS WHAT DOESN'T WORK ": rtID" - Does anyone know how to do this?
 If (o.RecordTypeId = : rtID) opptsToWorkOn.add(o); } } else{ for (Opportunity o : Trigger.new) { \\ #### I WOULD ALSO DO IT HERE! #########
If (o.RecordTypeId = : rtID) opptsToWorkOn.add(o); } }

 

Can someone point me in the right direction?

 

Thanks!

Greg

 

 

 

 

    \\ #### HERE IS WHAT DOESN'T WORK ": rtID" - Does anyone know how to do this?
Best Answer chosen by Admin (Salesforce Developers) 
kyle.tkyle.t

Try changing If (s.contains(o.RecordTypeId)) to If (s.contains(o.RecordType))

All Answers

Alok_NagarroAlok_Nagarro

Hi,

Go through the modified code given below :



// Create a list of RecordTypes we want to check for

List<RecordType> rtID = [SELECT Id FROM RecordType WHERE (SobjectType = 'Opportunity') AND (Name = 'Annuity' OR Name = 'Life'

OR Name='LTC' OR Name = 'TLC')];

// copy the list items in set
Set<RecordType> s=new Set<RecordType>();
s.addAll(rtId);


// Create a list for Opportunities that match our RecordType criteria
List<Opportunity> opptsToWorkOn = new List<Opportunity>();

// Loop through the Opportunities being updated or deleted and see if there are any
// for the record types we want.  

if(trigger.isDelete){
    for (Opportunity o : Trigger.old)    {
    
    
    If (s.contains(o.RecordTypeId))              
             opptsToWorkOn.add(o);    
      }
    }
    else{
      for (Opportunity o : Trigger.new) {
    \\ #### I WOULD ALSO DO IT HERE! #########
    If (s.contains(o.RecordTypeId))        
           opptsToWorkOn.add(o);    
      }
    }


Hope this helps.

Thanks,

gregusagregusa

Thanks for the help!

 

However, I get this error when I run s.contains(o.RecordTypeID)

 

Incompatible element type Id for collection of SOBJECT:RecordType

kyle.tkyle.t

Try changing If (s.contains(o.RecordTypeId)) to If (s.contains(o.RecordType))

This was selected as the best answer