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
subodh chaturvedi 17subodh chaturvedi 17 

how to Update the Child Records & parent Records (viceversa ) through trigger

Hi ,
can we Update the Records From parent to child & also  from child to parent  (viceversa ) through trigger .
I have a requirement where i have 10-15 Fields In parent Whose values i need to update in child fields &  fields with Same values  i have in child ,If I update any child field values from Child that should Update the values in parent. How We can do this through Trigger when record is Inserted & also While Updated ?  
Yuvaraj mayilsamy 9Yuvaraj mayilsamy 9
Hi Subodh,

 Yes we can. Provide more details on the field names and the exact requirement. We will be happy to help you.

Yuvaraj
Varun SinghVarun Singh
Hi 
subodh chaturvedi 17


Update child
 
trigger ContactUpdate on Account (after update) {
    Map < Id,  Account > mapAccount = new Map < Id, Account >();
    List<Contact> listContact = new List<Contact>();
    
    for(Account acct : trigger.new)
        mapAccount.put(acct.Id, acct);
    
    listContact = [ SELECT MailingStreet, MailingCity, AccountId FROM Contact WHERE AccountId IN : mapAccount.keySet() ];
    
    if ( listContact.size() > 0 ) {
        for ( Contact con : listContact ) {
            con.MailingStreet = mapAccount.get(con.AccountId).BillingStreet;
            con.MailingCity = mapAccount.get(con.AccountId).BillingCity;
        }
        update listContact;
    }
}

Update  parent
trigger CreateAccountFromContact on Contact (before insert) {
    //Collect list of contacts being inserted without an account
    List<Contact> needAccounts = new List<Contact>();
    for (Contact c : trigger.new) {
        if (String.isBlank(c.accountid)) {
            needAccounts.add(c);
        }
    }
    
    if (needAccounts.size() > 0) {
        List<Account> newAccounts = new List<Account>();
        Map<String,Contact> contactsByNameKeys = new Map<String,Contact>();
        //Create account for each contact
        for (Contact c : needAccounts) {
            String accountName = c.firstname + ' ' + c.lastname;
            contactsByNameKeys.put(accountName,c);
            Account a = new Account(name=accountName);
            newAccounts.add(a);
        }
        insert newAccounts;
        
        //Collect a new list of deal__c objects for new accounts
        //List<Deal__c> newRecsForAccounts = new List<Deal__c>();
        for (Account a : newAccounts) {
            //Put account ids on contacts
            if (contactsByNameKeys.containsKey(a.Name)) {
                contactsByNameKeys.get(a.Name).accountId = a.Id;
            }
            //Deal__c newRec = new Deal__c(name=a.Name, accountId=a.Id);
        }
        
        //insert newRecsForAccounts;
        
    }
    

}