0

I am using the below handler class in contact trigger to find the duplicate contacts, it checks only the lastName now if I want to check more than 2 or 3 filed then the only option I have is to create another set and then use it in the aggregate query, can someone please suggest if is there any better way to do the same instead of creating set per fields and also I have an after update trigger on account which query on contact object and update on account object and when a contact with account find duplicate contact instead of showing the custom error it shows the below error

ContactTrigger: execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 0010o00002J0iRVAAZ; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AccountTrigger: execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 0030o00002jA80yAAC; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, HEY! You cannot create duplicate contacts: []

public static void findDuplicatesusingAggregateFunction(List<Contact> newList, System.TriggerOperation triggerevent) {

        List<String> stringFirstName = new List<String>();
        SWITCH on triggerevent{
            WHEN BEFORE_INSERT, BEFORE_UPDATE{
                for(Contact record: newList) {
                    stringFirstName.add(record.LastName);
                }
                List<AggregateResult> duplicateFound = [SELECT Name FROM Contact WHERE lastName =:stringFirstName
                                                        GROUP by name having count(ID) >1];

                for(Contact cot: newList) {
                    if(!duplicateFound.isEmpty()) {
                        cot.addError('HEY! You cannot create duplicate contacts');
                    }
                }
            }
        }
    }

Could someone please suggest the right approach to find the duplicate contacts and also in case of contact has a parent record instead of showing the custom error it shows the above error

  • 3
    Best practice would be to make use of Duplicate rules. Is there any particular reason why you're avoiding using the tool that Salesforce is providing to you? Also, if you look at the end of that error message, you will see that your target error message is indeed included. The other parts of the error message you're getting is (as far as I know) largely unavoidable when trying to do this via a trigger. – Derek F Apr 15 '19 at 14:07
  • 1
    As Derek Mentioned, there is this amazing method findDuplicates which works on fuzzy matching rules and can help you with what you want. – Pranay Jaiswal Apr 15 '19 at 16:40

Your Answer

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

Browse other questions tagged or ask your own question.