0

as soon a I create account record I want to update the contact record's mailing address field. I have written trigger on account because if I update account address field automatically related contacts address field should update I have written this trigger m not finding result.

trigger createopp on Account (after insert,after update) {
    List<Contact> opp = New List<Contact>();
    set<id> ids=new set<id>();

    for(Account  con:trigger.new) {
        list<Contact> oppsi=[select id,mailingstreet,mailingcity,mailingstate,mailingpostalcode  from contact where accountid :con.id ];
        if(oppsi.size()==0){
            Contact opp1 = new Contact();
            opp1.AccountID= con.id;
            opp1.mailingstreet = con.Shippingstreet;
            opp1.mailingcity = con.Shippingcity;
            opp1.mailingstate = con.Shippingstate;
            opp1.mailingpostalcode =con.shippingpostalcode;
            opp.add(opp1);
        }
    }
    try {
        insert opp;
    } catch(Dmlexception e) {}
}
1

Please see code below and comments inside

trigger Account on Account (after insert, after update) {
    List<Contact> contactsForUpsert = New List<Contact>();

    // We want to avoid SOQL inside the for loop, because it might be a reason of troubles
    // and in order to follow best practices, thus we queried all needed information about Contacts
    // which are related with Accounts which are under insert/update
    // You have to think in 200 record's context when working with triggers
    // -->
    Map<Id, Contact> contactsByAccountId = new Map<Id, Contact>();
    List<Contact> contacts = [SELECT Id,
                                     AccountId,
                                     mailingstreet,
                                     mailingcity,
                                     mailingstate,
                                     mailingpostalcode
                            FROM Contact WHERE AccountId IN: Trigger.newMap.keySet()];
    for (Contact cont: contacts) {
        contactsByAccountId.put(cont.accountId, cont);
    }
    // <-- finished collecting information about Contacts. All contacts were placed in Map<AccountId, Contact>

    for (Account account: Trigger.new) {
        // old records are available only in update call
        Account old;
        if (Trigger.isUpdate) {
            old = Trigger.oldMap.get(account.Id);
        }
        // we want to perfoem the update of contact address fields in two cases:
        //  1. we insert new account, but there is a question: is that right business case for inserting Contact record here?
        //  2. we updated ShippingAddress in an exisitng account, I do believe that we do not want to update Contact record 
        //  each time when other fields were changed
        Boolean isShippingAddressChangedOrNew = Trigger.isInsert ? true :
                                                (   account.ShippingStreet != old.ShippingStreet
                                                 || account.ShippingCity != old.ShippingCity
                                                 || account.ShippingState != old.ShippingState
                                                 || account.ShippingPostalCode != old.ShippingPostalCode
                                                 || account.ShippingCountry != old.ShippingCountry) ? true : false;
        // check that field was changed
        if (isShippingAddressChangedOrNew) {
            // get existing Contact if exist
            Contact relatedContact = contactsByAccountId.get(account.Id);
            if (relatedContact == null) { // for insert call we create new Contact record
                relatedContact           = new Contact();
                relatedContact.AccountID = account.Id;
                relatedContact.LastName = 'test';
            }
            relatedContact.mailingstreet     = account.Shippingstreet;
            relatedContact.mailingcity       = account.Shippingcity;
            relatedContact.mailingstate      = account.Shippingstate;
            relatedContact.mailingpostalcode = account.shippingpostalcode;
            contactsForUpsert.add(relatedContact);
        }

    }

    try {
        upsert contactsForUpsert;
    } catch(Dmlexception e) {
        System.debug(LoggingLevel.ERROR, 'Contact insert from createopp.trigger has failed with message:' + e.getMessage());
    }
}

Read articles about trigger best practice:

8
  • I have record type ....may be that is the reason how to avoid that – Salesforce Learner Feb 22 '15 at 13:48
  • It's not working whenever i am editing shipping adress on account it should automatically update contact mailing adress – Salesforce Learner Feb 22 '15 at 13:53
  • @SalesforceLearner check a logs for errors, this code is working, I've tested it on fresh dev org. You might have troubles with validation, required fields, etc. – Pavel Slepiankou Feb 22 '15 at 13:55
  • Thanks for reply..It is not showing errors... it is not updating contact's mailing address with account's shipping address – Salesforce Learner Feb 22 '15 at 13:57
  • I have record type for account as well as contact ..may be that is the reason it is not updating and inserting – Salesforce Learner Feb 22 '15 at 14:01
0

You don't necessarily need a trigger for this. You can do this in under 10 minutes using the new Process Builder.

Create a Process that runs on the Account, add any criteria you think is applicable, then update the Contacts with the address entered on the Account.

The process would look something like this, except you'd add all the different fields for the address:

enter image description here

Let us know if you need your trigger diagnosed. There are a lot of problems with it, so you're better off using the Process Builder instead.

5
  • I am trying to do with trigger can you just help me with code – Salesforce Learner Feb 22 '15 at 12:32
  • In process bulder i cannot find shipping address field – Salesforce Learner Feb 22 '15 at 12:37
  • i have done that still it's not updating – Salesforce Learner Feb 22 '15 at 12:49
  • Did you Activate it? It works in my org – Nick Cook Feb 22 '15 at 12:57
  • Yeah I have activated – Salesforce Learner Feb 22 '15 at 12:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.