+ Start a Discussion
dmasondmason 

Adding record types to Apex Triggers

Hey Guys

I need some help

 

I have built the following apex trigger ( See below) however i need to apply the company search on a certain records types.

The Record types in question are  “FDMS Lead Generation  &  FDMS Sales Lead”, where do i add this into the code?

My apex trigger is


Trigger DuplicateLeadPreventer on Lead

                               (before insert, before update) {

 

    Map<String, Lead> leadMap = new Map<String, Lead>();

    for (Lead lead : System.Trigger.new) {

                               

        // Make sure we don't treat an Company name that 

       // isn't changing during an update as a duplicate. 

   

  if ((lead.company != null) &&

                (System.Trigger.isInsert ||

                (lead.company !=

                    System.Trigger.oldMap.get(lead.Id).company))) {

                               

            // Make sure another new lead isn't also a duplicate 

   

            if (leadMap.containsKey(lead.company)) {

                lead.company.addError('Another new lead has the '

                                    + 'same company name.');

            } else {

                leadMap.put(lead.company , lead);

            }

       }

    }

               

    // Using a single database query, find all the leads in 

   

    // the database that have the same company address as any 

   

    // of the leads being inserted or updated. 

   

    for (Lead lead : [SELECT company FROM Lead

                      WHERE company IN :leadMap.KeySet()]) {

        Lead newLead = leadMap.get(lead.company);

        newLead.company.addError('A lead with this company '

                               + 'name already exists.');

    }

}
  

dphilldphill
I would guess that you should add that check in before you add the fields to the leadMap. (You need to check by Id though and not RecordType.Name unless you requery for the Trigger.newData.)
BritishBoyinDCBritishBoyinDC

I'd try something like this...query for matching companies, put the names in Set, and then loop back through the trigger and flag the dupes - that way you can filter the company search in leads however you like, including by Record Type Name - e.g. 

 

Trigger DuplicateLeadPreventer on Lead (before insert, before update) {
 
    Map<String, Lead> leadMap = new Map<String, Lead>();
    for (Lead lead : Trigger.new) {
                               
        // Make sure we don't treat an Company name that 
       // isn't changing during an update as a duplicate. 
   
  if ((lead.company != null) &&
                (System.Trigger.isInsert ||
                (lead.company !=
                    System.Trigger.oldMap.get(lead.Id).company))) {
                               
            // Make sure another new lead isn't also a duplicate 
   
            if (leadMap.containsKey(lead.company)) {
                lead.company.addError('Another new lead has the '
                                    + 'same company name.');
            } else {
                leadMap.put(lead.company , lead);
            }
       }
    }
               
    /*
     Using a single database query, find all the leads in 
     the database that have the same company address as any 
     of the leads being inserted or updated. 
   
   */
   
    Set<String> ExistingCompanies = new Set<String> ();

            for (Lead l: [Select Id, Company from Lead WHERE Company IN :leadMap.keyset()
                             AND RecordType.Name IN ('Test 1', 'Test 2')]) {
            ExistingCompanies.add(l.Company);
            }

    for (Lead l : Trigger.new) {
        if (ExistingCompanies.contains(l.company) ) {
             l.company.addError('A lead with this company '
                               + 'name already exists.');
        }
    }
}

 

BritishBoyinDCBritishBoyinDC

Just noted you are actually looking for existing leads with same company my mistake. Have updated code to match requirement...

dmasondmason

HI Thank you for providing me the coding to incorporate the two record types. I implemented your code into my sandbox and i added the correct record types to the code, however when i create a lead from any of the following record types it

AIBMS  

EMS Card Not Present  

EMS Card Present  

EMS New  

FDGL

I still recieve the following error message -Error: A lead with this company name already exists.

Ideally i only need this trigger to search all leads which have the following record type

FDMS eMAX  

FDMS Lead Generation  

FDMS Lead with Health Check

 FDMS Sales Lead  

FDMS Standard Lead

 

can you help ?

BritishBoyinDCBritishBoyinDC

Just to clarify - did you just want all the logic to only apply to the second list of record types, or did you want all leads to be checked, but only rejected if there a existing company for leads with a record type in list two...? Sounds like you only wants leads with Record Types in the second list to be checked for dupes?

 

If so, there are a couple of things to consider. As a previous post mentioned, triggers only have the Record Type Id - so if you want to when we filter by record type name, you need to match the Id with the name - which you can do a with a describe call on the lead object - I can post an example if you need one.

 

But I am thinking a better approach would be to store the Record Type Ids you want to be checked in a custom setting. That way, if a new record type is added tomorrow, you don't need to update your code - you just need to add a new record to the custom setting, and it will be included in both the initial check and the query.

 

Let me know, and I can post some snippets to help you get there...   

dmasondmason

HI BritishBoyinDc



I just want the logic to apply to those record types listed. So if a Burger King Limited is saved on the “FDMS Lead Generation or FDMS Sales Lead, and a new lead of Burger king Limited is trying to be saved on the FDMS Lead Generation or FDMS Sales Lead record type, then the trigger would advise the user, that that lead is already in the database under those two record types

What do you think be the easiest given my situation above ?

BritishBoyinDCBritishBoyinDC

So I would do something like this...create a new Custom Setting, and store the Record Type Ids you want the logic to apply to in the default name field for that setting.  I would then add a check in the first loop to see if the record type for the lead in the trigger is in that setting - if so, go ahead and process it. 

 

I would then also update the search query to query for leads with record types stored in the setting. 

 

It ends up looking something like this, where the new setting is called Manage_Lead_Dupes.  That way, you can just add a new record type to the setting, and it will be included in the logic. Note - in testing this, it is important to store the 18 character version of the Record Type Id (the one the API uses) in the Custom Setting, otherwise they won't match. 

 

Trigger DuplicateLeadPreventer on Lead
                               (before insert, before update) {
 
 //Get map of record types we care about from Custom Setting
 Map<String, Manage_Lead_Dupes__c> leadrtmap = Manage_Lead_Dupes__c.getAll();
 
 //Since only certain leads will match, put them in a separate list
 List<Lead> LeadstoProcess = new List<Lead> ();
 
 //Company to Lead Map
 Map<String, Lead> leadMap = new Map<String, Lead>();
 
    for (Lead lead : Trigger.new) {
     
     //Only process for Leads in our RecordTypeMap
         if (leadrtmap.keyset().contains(lead.RecordTypeId) ) {
                               
        // Make sure we don't treat an Company name that 
       // isn't changing during an update as a duplicate. 
   
              if (
                 (lead.company != null) &&
                 (Trigger.isInsert ||
                 (lead.company != Trigger.oldMap.get(lead.Id).company))
                 ) 
                 {
                                       
                    // Make sure another new lead isn't also a duplicate 
           
                        if (leadMap.containsKey(lead.company)) {
                            lead.company.addError('Another new lead has the '
                                            + 'same company name.');
                        } else {
                            leadMap.put(lead.company , lead);
                            LeadstoProcess.add(lead);
                        }
                }
    } //end RT If Check
    } //End Loop
               
    /*
     Using a single database query, find all the leads in 
     the database that have the same company address as any 
     of the leads being inserted or updated. 
   
   */
   
    Set<String> ExistingCompanies = new Set<String> ();

            for (Lead l: [Select Id, Company from Lead WHERE Company IN :leadMap.keyset()
                             AND RecordTypeId IN :leadrtmap.keyset()]) {
                          ExistingCompanies.add(l.Company);
                }

    //Now loop through leads to process, since we should only loop if matches
    for (Lead l : LeadstoProcess) {
        if (ExistingCompanies.contains(l.company) ) {
             l.company.addError('A lead with this company '
                               + 'name already exists.');
        }
    }
}

 

dphilldphill
Instead of using custom settings, you could just use the Schema to put those items into a Map for the RecordType Names and Record Type Ids to associate with each other. If you are too lazy, you could just do a simple query to grab the two records and toss into a map also. (at the very beginning)
dmasondmason

Hi Guys

Thank you for your email

I had to mend your code slightly and the amended code is

 

Trigger DuplicateLeadPreventer on Lead
                               (before insert, before update) {

//Get map of record types we care about from Custom Setting
 Map<String, Manage_Lead_Dupes_C__c> leadrtmap = Manage_Lead_Dupes_C__c.getAll();

 

 
 //Since only certain leads will match, put them in a separate list
 List<Lead> LeadstoProcess = new List<Lead> ();
 
 //Company to Lead Map
 Map<String, Lead> leadMap = new Map<String, Lead>();
 
    for (Lead lead : Trigger.new) {
    
     //Only process for Leads in our RecordTypeMap
         if (leadrtmap.keyset().contains(lead.RecordTypeId) ) {
                              
        // Make sure we don't treat an Company name that
       // isn't changing during an update as a duplicate.
  
              if (
                 (lead.company != null) &&
                 (Trigger.isInsert ||
                 (lead.company != Trigger.oldMap.get(lead.Id).company))
                 )
                 {
                                      
                    // Make sure another new lead isn't also a duplicate
          
                        if (leadMap.containsKey(lead.company)) {
                            lead.company.addError('Another new lead has the '
                                            + 'same company name.');
                        } else {
                            leadMap.put(lead.company , lead);
                            LeadstoProcess.add(lead);
                        }
                }
    } //end RT If Check
    } //End Loop
              
    /*
     Using a single database query, find all the leads in
     the database that have the same company address as any
     of the leads being inserted or updated.
  
   */
  
    Set<String> ExistingCompanies = new Set<String> ();

            for (Lead l: [Select Id, Company from Lead WHERE Company IN :leadMap.keyset()
                             AND RecordTypeId IN :leadrtmap.keyset()]) {
                          ExistingCompanies.add(l.Company);
                }

    //Now loop through leads to process, since we should only loop if matches
    for (Lead l : LeadstoProcess) {
        if (ExistingCompanies.contains(l.company) ) {
             l.company.addError('A lead with this company '
                               + 'name already exists.');
        }
    }
}

Also building a custom setting i realised that the name has to be the unique 18digit code, and the Record types needs to be the name

I Put the name as the record type and the record type as the id

Whoopsie