function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Shubham SengarShubham Sengar 

trigger problem 5

write a trigger will prevent user from creating a lead that already existing as a contact .?
hint:: we will use leads/contacts email address to detact duplicates
Best Answer chosen by Shubham Sengar
Shubham SengarShubham Sengar
trigger FindDupes on Lead (before insert, before update)
 {
  for (Lead myLead : Trigger.new)
   {
    if (myLead.Email != null)
     {
List<Contact> dupes = [SELECT Id FROM Contact WHERE Email = :myLead.Email];
 if(dupes.size()>0)
{
trigger.new[0].id.addError('lead already Exist as a contact ');
}
}
}
 }

 

All Answers

KaranrajKaranraj
I encourage you to take a look into the trailhead module about apex trigger - https://developer.salesforce.com/trailhead/force_com_dev_beginner/apex_triggers/apex_triggers_intro 
Try on your own, if you are really stuck with any error message or any problem, please share it here we are here to help you. 
Shubham SengarShubham Sengar

trigger FindDupes on Lead (before insert, before update) { for (Lead myLead : Trigger.new) {
if (myLead.Email != null) {
List<Contact> dupes = [SELECT Id FROM Contact WHERE Email = :myLead.Email];
if (dupes.size() > 0) {
myLead.Dupe_Contact__c = dupes[0].Id;
} else {
myLead.Dupe_Contact__c = null;
} }
} }

but its gives error
[Error] Error: Compile Error: Invalid field Dupe_Contact__c for SObject Lead at line 7 column 9
Shubham SengarShubham Sengar
hi karanraj are u there ..
Shubham SengarShubham Sengar
trigger FindDupes on Lead (before insert, before update)
 {
  for (Lead myLead : Trigger.new)
   {
    if (myLead.Email != null)
     {
List<Contact> dupes = [SELECT Id FROM Contact WHERE Email = :myLead.Email];
 if(dupes.size()>0)
{
trigger.new[0].id.addError('lead already Exist as a contact ');
}
}
}
 }

 
This was selected as the best answer