+ Start a Discussion
F SmoakF Smoak 

Update child records based on update in parent record and vice versa


I have a req where I am automating creation of records for object A. So I have basically added a trigger(after insert,after update) on object B ( wh/ich contains object A Lookup) which automates creation of object A once some attributes(newly created on B to have attributes populated for creation of A) populated on B and also populates the same lookup with obj A ID newly automated. This also handles that when obj B is updated, marks the updates in obj A to keep both in sync. However end user has option to manually create obj A records so I wanted to ensure obj A changes reflect on obj B. But I think this will be recursive loop and wont be feasible. Is there any option to achieve this? Please help!
AbhishekAbhishek (Salesforce Developers) 
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)) {
    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;
            Account a = new Account(name=accountName);
        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;


Try the above code for your requirement, You may have to make some minor changes to it.

Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.