0

I have a list of standard Lead records that are being imported via Data Loader. On the Lead object I have a before trigger that calls an Apex class that passes in the records to the class method shown below via Trigger.New

I want to run a SOQL query against the Lead object to see if any of the records in my incoming list have the same email address and were created within the last 15 hours.

If there is a record with the same email and it was created within the last 15 hours then do nothing, otherwise just insert the lead record.

public static void checkLeads(List<Lead> leads) {

   Id AgentLeadRecordTypeId = Schema.SObjectType.Lead.getRecordTypeInfosByName().get('Agent').getRecordTypeId();

   List<Lead> agentLeadList= new List<Lead>();

   for (Lead lead : leads) {

        // if this is an agent lead
        if( lead.RecordTypeId == AgentLeadRecordTypeId ) {
            agentLeadList.add( lead );
        }
    }

    //now I have a list of lead records to check against ...
       ......   .......

}  // end checkLeads method
0

Architecturally speaking, your conception of how this trigger should work is slightly off. It is not possible to "do nothing" versus inserting the records. What you actually need to do is add an error to the record so it fails to save (doing nothing in the database). If you set up your data load to allow partial success, then this approach will allow only records with no duplicates to hit the system.

As for the actual logic, you should be collecting the filter values, not records. Typically, you would use a Set<String> and add lead.Email here. You will need to also store a Datetime threshold variable to filter against. Something like:

Step 1: Get Filter Values

Set<String> emails = new Set<String>();
for (Lead record : trigger.new)
{
    if (someCondition)
    {
        emails.add(lead.Email);
    }
}

Step 2: Query Existing Records

Datetime threshold = Datetime.now().addHours(-15);
Set<String> existingEmails = new Set<String>();
for (Lead existingRecord : [
    SELECT Email FROM Lead WHERE CreatedDate > :threshold AND Email IN :emails
]){
    existingEmails.add(existingRecord.Email);
}

Step 3: Prevent Duplicate Save

for (Lead record : trigger.new)
{
    if (existingEmails.contains(record.Email))
    {
        record.addError('Use an informative error message here');
    }
}

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.