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
ManjusrinuManjusrinu 

Updating count field on lead

Hi ,

I am trying to prevent duplicate email and at the same time i am updating count field on lead when i give the same email ..

The count should update on the existing email lead record .I am getting count updated value in debug logs,but on the record .

Can anyone help me out ?..

Trigger :

trigger LeadTrigger on Lead (before insert, before update) {
    if(trigger.isInsert || trigger.isUpdate) { 
    Leaddupliacateemailpreventor dupEmail = new Leaddupliacateemailpreventor();
    dupEmail.duplicateEmail(trigger.new);
    }
    }
    
Helper class :
public class Leaddupliacateemailpreventor {
    public void duplicateEmail (List<Lead> Records) {
        Map<string,Lead> leadRecords = new Map<string,Lead>();
        List<Lead> myLeads = new List<Lead>();
        myLeads = [SELECT id,Email ,Email_count__c from Lead where Email != null];
        for(Lead ll :myLeads) {
            if(!(leadRecords.containsKey(ll.Email))) {
                leadRecords.put(ll.Email ,ll); 
            }
        }
        system.debug('ssssssssssss' + leadRecords.keySet());
        for(Lead newRecord : Records) {
            if(leadRecords.ContainsKey(newRecord.Email)) { 
                newRecord.Email.addError('Email exists'); 
                if( leadRecords.get(newRecord.Email).Email_count__c != null ) {
                    leadRecords.get(newRecord.Email).Email_count__c = leadRecords.get(newRecord.Email).Email_count__c +1;
                } 
                else {
                    leadRecords.get(newRecord.Email).Email_count__c = 1;
                }
            } 
            System.debug('hhhhhh   ' + leadRecords.get(newRecord.Email).Email_count__c );
        } 
    }
}

ANUTEJANUTEJ (Salesforce Developers) 
Hi Manju,

Can you elaborate on the issue you are facing or the scenario you are implementing so as to check further and respond back.

Thanks.
ManjusrinuManjusrinu
Whenever I am inserting or updating lead records,If I give same email which is already existing I should throw error email already exists , and at the same time I should update a field called email count (in the existing email record ) . I am able to throw the error message ,but can't able to update email count field .
Andrew GAndrew G


from the manual
SObject Class | Apex Developer Guide | Salesforce Developers (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_sobject.htm)

addError(errorMsg)
Marks a trigger record with a custom error message and prevents any DML operation from occurring.

so, in short, you can't have your cake and eat it it too...... or in this case, you can't have your error message and update your record too.


regards
Andrew