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
Shruthi MN 88Shruthi MN 88 

Code noy working

HI Everyone,

I have written a handler class and a trigger on the below senario. Code is not working

Created two feilds on Contact Ratilg__c and Site__c. Now once a contact is created the contact should search for the site name of the account which is entered on site__c  of the contact and associat the account with the contact. Then update the accounts Rating feild  as per the contact Rating__c feild.

Below is the code that I have written

Handl;er class

public class ContactTriggerHandler {
    public static void handleAfterInsert(List<Contact> newContacts) {
        Map<String, String> contactSiteRatingMap = new Map<String, String>();
        for (Contact newContact : newContacts) {
            if(newContact.AccountId == null && newContact.Site__c != null && newContact.Rating__c != null){
                contactSiteRatingMap.put(newContact.Site__c, newContact.Rating__c);
            }
        }
        if (!contactSiteRatingMap.isEmpty()) {
            List<Account> matchingAccounts = [SELECT Id, Site, Rating FROM Account
                                              WHERE Site IN :contactSiteRatingMap.keySet() AND 
                                              Rating IN :contactSiteRatingMap.values()];
            List<Contact> contactsToUpdate = new List<Contact>();
            for (Contact newContact : newContacts) {
                if (newContact.AccountId == null && newContact.Site__c != null && newContact.Rating__c != null) {
                    for (Account matchingAccount : matchingAccounts) {
                        if (newContact.Site__c == matchingAccount.Site && newContact.Rating__c == matchingAccount.Rating) {
                            newContact.AccountId = matchingAccount.Id;
                            contactsToUpdate.add(newContact);     
                        }
                    } 
                }
            }
            if (!contactsToUpdate.isEmpty()) {
                
                update contactsToUpdate;                
            }
        }  
    }  


Trigger
trigger ContactTrigger on Contact(after insert)
{
    ContactTriggerHandler.handleAfterInsert(Trigger.new);
}
HarshHarsh (Salesforce Developers) 
Hi Shruthi, 
It is a duplicate question, Please refer below link for another one.

https://developer.salesforce.com/forums/ForumsMain?id=9065d0000007BNU