Below is the sample code for the same try to change according to your requirements.
trigger CaseAfterInsertUpdate on Account(after insert, after update) {
List<Contact> accList = new List<Contact>();
Map<Id,List<Contact>> AccountMap = new Map<Id,List<Contact>>();
if(Trigger.isUpdate){
for(Contact con : [SELECT Id,AccountId FROM C0ntact WHERE AccountId IN :Trigger.newMap.keySet()])
if(!AccountMap.containskey(con.AccountId){
AccountMap.put(con.AccountId,new List<Contact>());
}
AccountMap.get(con.AccountId).add(con);
}
}
for(Account c:Trigger.new) {
system.debug('hfeffht'+c.ID);
if(!AccountMap.containskey(c.Id)) { //code for insert only
Contact con = new Contact(LastName=c.Name,
MailingStreet=c.BillingStreet,
MailingCity=c.BillingCity,
MailingPostalCode=c.BillingPostalCode,
MailingCountry=c.BillingCountry,
AccountId=c.ID);
accList.add(con);
system.debug('AccountId'+con.AccountId);
}else { //code for update account
for(Contact con : AccountMap.get(c.Id)){ //get all contacts under account and update.
con.MailingCity = c.BillingCity;
con.MailingPostalCode = c.BillingPostalCode;
con.MailingCountry = c.BillingCountry;
accList.add(con);
}
}
}
try {
upsert accList;
} catch (Exception ex) {
System.debug('Could not update Last Survey Sent field on Account with cause: ' + ex.getCause());
}
}
Below is the sample code for the same try to change according to your requirements.
Best Regards,
Sandhya
Hope this will help you
Thank you
Ajay Dubedi