0

This is my first question here. I'm working with a company that allows duplicate leads, but they want all the duplicate leads to have the same owner. I'm trying to write a before insert, before update trigger, but I can't make it work. Some help would be awesome!!

Thank you so much!!!

Here's a sample of my trigger.

trigger DuplicateLeadOwner on Lead (before insert, before update) {
String leadEmail;
String leadId;
List <Lead> dupeleads = [SELECT Id, OwnerId FROM Lead WHERE Email = :leadEmail AND Id != :leadId];
for(Lead l : Trigger.new){
    //Make sure the lead has an email address
    if (l.Email != null){
        //Find a duplicate
        String leadEmail = l.Email;
        String leadId = l.Id;
        
        //If a duplicate is found, update the Owner field.
        if(dupeleads.size() > 0){
            dupeleads[0].OwnerId = l.OwnerId;
            dupeleads[0].Email = l.Email;
        }
    }
}

}

0

You forgot to aggregate the emails you want to query, as I demonstrate in my Aggregate-Query-Update Pattern blog post. Note also that your code was not bulkified.

Set<String> emails = new Set<String>();
Map<String, Id> ownerIds = new Map<String, Id>();
Id ownerId;
// Aggregate Values to Query
for(Lead record: Trigger.new) {
  emails.add(record.Email);
}
// Ignore null
emails.remove(null);
// Query matching records
for(Lead record: [SELECT Email, OwnerId FROM Lead WHERE Email = :emails AND Id != :Trigger.new]) {
  ownerIds.put(record.Email, record.OwnerId);
}
// Update records in trigger
for(Lead record: Trigger.new) {
  if((ownerId = ownerIds.get(record.Email)) != null) {
    record.OwnerId = ownerId;
  }
}
3
  • Hello @sfdcfox Thank you so much for the answer!! I'm getting an error with your trigger in the last if statement. It says "Illegal assignment from Boolean to Id". I tried to fix it but couldn't. Could you please check and let me know what's wrong? Thanks again for your help!! – Ernesto Pastura Mar 20 at 2:25
  • @ErnestoPastura There was a missing parentheses, it seems. Try that. – sfdcfox Mar 20 at 2:31
  • Hello @sfdcfox! Now the syntax is correct, but in stead of changing the ownership of the rest of the duplicates when I assign ownership to one record, it doesn't let me change ownership. It automatically come back the the previous owner. Sorry, but I can't figure out why. – Ernesto Pastura Mar 20 at 18:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.