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
Sridhar ReddySridhar Reddy 

Need help on trigger with Map collection

Hi All, 

Follwing trigger is not working ,Can someone help ?
I couldn't find much in the debug log except a query run.

(following snippet can be simply pasted in the dev org for quick review )

 

trigger A_ConPhoneFromCON on Contact (before insert, before update) {

    // Create a map to store the Account IDs and their corresponding phone numbers
    Map<Id, contact> accountIdToPhone = new Map<Id, contact>();

    for (Contact updatedContact : Trigger.new) {
        // Check if the Contact has an associated Account
        if (updatedContact.AccountId != null) {
            // Add the related Account's ID and phone number to the map
            accountIdToPhone.put(updatedContact.AccountId, updatedContact);
        }
    }

    // Retrieve the related Account records and update the Contacts' phone numbers
    List<Account> relatedAccounts = [SELECT Id, Phone FROM Account WHERE Id IN :accountIdToPhone.keySet()];

    for (Contact updatedContact : Trigger.new) {
        // Check if the Contact is associated with an Account
        if (updatedContact.AccountId != null) {
            // Update the Contact's phone number with the related Account's phone number
            updatedContact.Phone = accountIdToPhone.get(updatedContact.AccountId).phone;
        }
    }
}
Best Answer chosen by Sridhar Reddy
Abdul KhatriAbdul Khatri
Hi Sridhar,

Please use the below code. I made the following changes in your code
  • Use Map instead of List on Account SOQL
  • Change the last line from accountIdToPhone to relatedAccounts.
trigger A_ConPhoneFromCON on Contact (before insert, before update) {
    
    // Create a map to store the Account IDs and their corresponding phone numbers
    Map<Id, contact> accountIdToPhone = new Map<Id, contact>();
    
    for (Contact updatedContact : Trigger.new) {
        // Check if the Contact has an associated Account
        if (updatedContact.AccountId != null) {
            // Add the related Account's ID and phone number to the map
            accountIdToPhone.put(updatedContact.AccountId, updatedContact);
        }
    }
    
    // Retrieve the related Account records and update the Contacts' phone numbers
    Map<Id, Account> relatedAccounts = new Map<Id, Account>([SELECT Id, Phone FROM Account WHERE Id IN :accountIdToPhone.keySet()]);
    
    for (Contact updatedContact : Trigger.new) {
        // Check if the Contact is associated with an Account
        if (updatedContact.AccountId != null) {
            // Update the Contact's phone number with the related Account's phone number
            updatedContact.Phone = relatedAccounts.get(updatedContact.AccountId).phone;
        }
    }
}

I hope this help.