[SalesForce] After Update Trigger on Account to create contact

I am writing a trigger to auto create a contact once the account is created. Also I would like to update all the existing accounts so that it will create contacts only once(Further updates of account should not create one more contact). I am stuck on how to write after update trigger. Here is the code that I have written so far. Any help in the code could be helpful.

trigger BillingContacts on Account (after insert , after update){

if(trigger.isinsert && trigger.isafter)    {

    List<Contact> ct = new List <Contact>();

    for(Account acc : trigger.new){

        Contact c = new Contact(LastName = acc.name + '-' +'Billing Contact',
                    AccountId=acc.id,
                    Fax=acc.Fax,
                    Phone=acc.Phone,
                    Contact_Type__c = true,
                    MailingStreet=acc.BillingStreet,
                    MailingCity=acc.BillingCity,
                    MailingState=acc.BillingState,
                    MailingPostalCode=acc.BillingPostalCode,
                    MailingCountry=acc.BillingCountry,
                    );

        ct.add(c);
    }
    insert ct;
    } 

    if(trigger.isupdate && trigger.isafter){

    }

}

Best Answer

You can try the below code.

if(trigger.isupdate && trigger.isafter){
    List<Contact> ct = new List <Contact>();
    Map<Id,Boolean> mapCheck = new Map<Id,Boolean>();
    for(Contact c : [SELECT LastName,AccountId FROM Contact WHERE AccountId IN : trigger.new]) {
        mapCheck.put(c.AccountId,true);
        if(c.LastName.contains('Billing Contact'))
            mapCheck.put(c.AccountId,false);
    }
    for(Account acc : trigger.new){
        if(mapCheck.get(acc.Id)) {
            Contact c = new Contact(LastName = acc.name + '-' +'Billing Contact',
                        AccountId=acc.id,
                        Fax=acc.Fax,
                        Phone=acc.Phone,
                        Contact_Type__c = true,
                        MailingStreet=acc.BillingStreet,
                        MailingCity=acc.BillingCity,
                        MailingState=acc.BillingState,
                        MailingPostalCode=acc.BillingPostalCode,
                        MailingCountry=acc.BillingCountry,
                        );
            ct.add(c);
        }
    }
    insert ct;
}

My only concern is for each Contact the mapCheck will be updated in the first for loop with its accountid as key and true as value.

I can't think of any better way to avoid this.