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
Vethanbu LibertinVethanbu Libertin 

Write trigger that country (custom field) field of account object  should get copied with the value of country(custom field) of contact object whenever a contact is created or account is updated

Write trigger that country (custom field) field of account object  should get copied with the value of country(custom field) of contact object whenever a contact is created or account is updated

 
Best Answer chosen by Vethanbu Libertin
Shri RajShri Raj
trigger UpdateAccountCountry on Contact (after insert, after update) {
    Set<Id> accountIds = new Set<Id>();

    // Get the Account Ids from the inserted/updated Contacts
    for (Contact contact : Trigger.new) {
        accountIds.add(contact.AccountId);
    }

    // Query the Accounts
    List<Account> accounts = [SELECT Id, Country__c FROM Account WHERE Id IN :accountIds];

    // Map the Accounts to their Ids
    Map<Id, Account> accountMap = new Map<Id, Account>();
    for (Account account : accounts) {
        accountMap.put(account.Id, account);
    }

    // Update the Accounts
    for (Contact contact : Trigger.new) {
        Account account = accountMap.get(contact.AccountId);
        if (account != null) {
            account.Country__c = contact.Country__c;
        }
    }

    // Update the Accounts
    update accounts;
}

 

All Answers

Shri RajShri Raj
trigger UpdateAccountCountry on Contact (after insert, after update) {
    Set<Id> accountIds = new Set<Id>();

    // Get the Account Ids from the inserted/updated Contacts
    for (Contact contact : Trigger.new) {
        accountIds.add(contact.AccountId);
    }

    // Query the Accounts
    List<Account> accounts = [SELECT Id, Country__c FROM Account WHERE Id IN :accountIds];

    // Map the Accounts to their Ids
    Map<Id, Account> accountMap = new Map<Id, Account>();
    for (Account account : accounts) {
        accountMap.put(account.Id, account);
    }

    // Update the Accounts
    for (Contact contact : Trigger.new) {
        Account account = accountMap.get(contact.AccountId);
        if (account != null) {
            account.Country__c = contact.Country__c;
        }
    }

    // Update the Accounts
    update accounts;
}

 
This was selected as the best answer
Vethanbu LibertinVethanbu Libertin
thank you