• RK29
  • NEWBIE
  • 10 Points
  • Member since 2017

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 1
    Replies
Hi All,
I have created a trigger that checks to see if another Lead or Contact has the exact same name. How can I avoid the for loop inside for loop to compare old and new lead values and avoid running SOQL inside loop to get matching contacts? Code below:
 
trigger DuplicateLeadOrContact on Lead (before insert) {
    list<Lead> leadList = new list<Lead>();
    list<Contact> conList = new list<Contact>();
    leadList = [SELECT Id, firstname, lastname from LEAD];
    for(Lead myLead : Trigger.New){
        if(myLead.firstName != null && myLead.lastName != null){
            for(Lead oldLead : leadList){
                if(myLead.firstName == oldLead.firstname && myLead.lastName == 
           oldLead.lastName){
                    myLead.addError('Lead already Exists with same Lead first 
               name and last name');
                }

            }

        }
        conList = [SELECT Id, firstname, lastname from Contact where firstname 
        =:myLead.firstName AND lastName =:myLead.lastName];
        if(conList.size() > 0){
            myLead.addError('Lead already Exists with same Contact first name 
        and last name');
        }
       }


}

 
  • March 17, 2018
  • Like
  • 0
Hi All,
I have created a trigger that checks to see if another Lead or Contact has the exact same name. How can I avoid the for loop inside for loop to compare old and new lead values and avoid running SOQL inside loop to get matching contacts? Code below:
 
trigger DuplicateLeadOrContact on Lead (before insert) {
    list<Lead> leadList = new list<Lead>();
    list<Contact> conList = new list<Contact>();
    leadList = [SELECT Id, firstname, lastname from LEAD];
    for(Lead myLead : Trigger.New){
        if(myLead.firstName != null && myLead.lastName != null){
            for(Lead oldLead : leadList){
                if(myLead.firstName == oldLead.firstname && myLead.lastName == 
           oldLead.lastName){
                    myLead.addError('Lead already Exists with same Lead first 
               name and last name');
                }

            }

        }
        conList = [SELECT Id, firstname, lastname from Contact where firstname 
        =:myLead.firstName AND lastName =:myLead.lastName];
        if(conList.size() > 0){
            myLead.addError('Lead already Exists with same Contact first name 
        and last name');
        }
       }


}

 
  • March 17, 2018
  • Like
  • 0