I'm really new to this platform (one week barely, although the programming logic is the same for everything) and I'm not able to solve this.
I have added two new choices to the Type picklist of the Account object "First" and "Last", When a pick "First" I need to get the address from the first contact related to that account, and when "Last" the last address from the last contact related to that account.
trigger UpdateAddress on Account (before insert, before update) {
Set<String> firstAccountIds = new Set<String>();
Set<String> lastAccountIds = new Set<String>();
List<Account> accList = new List<Account>();
List<Contact> contactList = new List<Contact>();
Account acc;
Map<String, String> mapBillingStreet = new Map<String, String>();
Map<String, String> mapBillingCity = new Map<String, String>();
Map<String, String> mapBillingState = new Map<String, String>();
Map<String, String> mapBillingCountry = new Map<String, String>();
Map<String, String> mapBillingPostalCode = new Map<String, String>();
for(Account acc : trigger.new) {
if(acc.Type == 'First') {
firstAccountIds.add(acc.Id);
} else if (acc.Type == 'Last') {
lastAccountIds.add(acc.Id);
}
}
for(Contact firstContact: [SELECT Id, AccountId, MailingStreet, MailingCity, MailingState, MailingCountry, MailingPostalCode FROM Contact WHERE AccountId IN :accList ORDER BY CreatedDate ASC LIMIT 1]) {
mapBillingStreet.put(firstContact.AccountId, firstContact.MailingStreet);
mapBillingCity.put(firstContact.AccountId, firstContact.MailingCity);
mapBillingState.put(firstContact.AccountId, firstContact.MailingState);
mapBillingCountry.put(firstContact.AccountId, firstContact.MailingCountry);
mapBillingPostalCode.put(firstContact.AccountId, firstContact.MailingPostalCode);
}
for(Contact lastContact: [SELECT Id, AccountId, MailingStreet, MailingCity, MailingState, MailingCountry, MailingPostalCode FROM Contact WHERE AccountId IN :accList ORDER BY CreatedDate DESC LIMIT 1]) {
mapBillingStreet.put(lastContact.AccountId, lastContact.MailingStreet);
mapBillingCity.put(lastContact.AccountId, lastContact.MailingCity);
mapBillingState.put(lastContact.AccountId, lastContact.MailingState);
mapBillingCountry.put(lastContact.AccountId, lastContact.MailingCountry);
mapBillingPostalCode.put(lastContact.AccountId, lastContact.MailingPostalCode);
}
if(!accList.IsEmpty()){
update accList;
}
}
I came to this cuz a recommendation of a coworker, but it doesn't work and I think is too robust.
Please help, the company is testing me.