Activity Forums Salesforce® Discussions Why do I'm getting an error on inserting and updating the address in contact mailing address?

  • Why do I'm getting an error on inserting and updating the address in contact mailing address?

    Posted by Deepak on March 4, 2020 at 1:41 pm
    trigger ContactMailAddr on Contact (after insert, after update) 
    {
        // first you create a list to store the Account ids
        List<Id> accountToSearch = new List<Id>();
        
        // get them from the contacts
        for (Contact contact : Trigger.new)
        {
            accountToSearch.add(contact.AccountId);
        }
        // query in the db
        List<Account> accounts = [SELECT Id, BillingStreet, BillingCity, BillingState, BillingCountry, BillingPostalCode FROM Account WHERE Id IN :accountToSearch];
        list<contact> contacts =new list<contact>([select id,AccountId,MailingCity,MailingState,MailingStreet,MailingCountry
                                                   from contact where accountid in :accountToSearch]);
        // iterate over the accounts and contacts
        for (Account account : accounts)
        {
            for (Contact contact : Trigger.new)
            {
                // if a contact is set to the account then
                if (contact.AccountId == account.Id && contact.AccountId != null)
                {
                    // copy the contact's address to the account's fields
                    contact.MailingStreet = account.BillingStreet;
                    contact.MailingCountry =  account.BillingCountry;
                    contact.MailingState =  account.BillingState;
                    contact.MailingCity =  account.BillingCity;
                    contact.MailingPostalCode = account.BillingPostalCode;
                    
                }
            }
        }
        // finally update the contacts records
        update contacts;
    }

    I'm getting an error on inserting and updating the address?

    Deepak replied 4 years, 8 months ago 1 Member · 0 Replies
  • 0 Replies

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos

Popular Salesforce Infographics