I'm working on trigger that will [after insert] get Street from ContactPointAddress object connected via lookup (Contact__c) and re-write MailingStreet field in Contact object ONLY if checkbox isDefault is checked. This is what I've done so far:
public static void AfterInsert(ContactPointAddress[] lstContactPointAddresses)
{
List<Contact> allPassagersToBeUpdated= new List<Contact>();
for (ContactPointAddress tmpContactPointAddress : lstContactPointAddresses)
{
// created contactPointAddress is checked - is default
if (tmpContactPointAddress.IsDefault == true) {
Contact passenger = [SELECT Name,LastName,MailingStreet FROM Contact WHERE Id =: tmpContactPointAddress.Contact__c];
Address addressCompoundField = (Address)tmpContactPointAddress.Address;
passenger.MailingStreet = addressCompoundField.Street;
allPassagersToBeUpdated.add(passenger);
}
else {
return;
}
}
if(allPassagersToBeUpdated.size()>0){
update allPassagersToBeUpdated;
}
}
The problem is, my compound field Addres in Contact Point Address is always null. I don't know why as I can acces values of other fields. Can anyone help me please? Thanks a lot:)
p.s: my exact error is:
Trg_ContactPointAddress: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object Class.Trg_ContactPointAddress_Handler.AfterInsert: line 31, column 1 Trigger.Trg_ContactPointAddress: line 14, column 1
I tried to re-arrange the code in order to save SOQL calls to database and end up with sth like this:
public static void AfterInsert(ContactPointAddress[] lstContactPointAddresses) {
List<Contact> allPassengersToBeUpdated = new List<Contact>();
set<Id> setOfPassengersIds = new set<Id>();
for (ContactPointAddress tmpContactPointAddress : lstContactPointAddresses) {
// created contactPointAddress is checked - is default
if (tmpContactPointAddress.IsDefault == true) {
setOfPassengersIds.add(tmpContactPointAddress.Contact__c);
} else {
return;
}
}
map<Id, Contact> mapPassengers = new map<Id, Contact>([SELECT Id, MailingStreet FROM Contact WHERE Id IN :setOfPassengersIds ]);
map<Id, ContactPointAddress> mapCPA = new map<Id, ContactPointAddress>([SELECT Id, Address FROM ContactPointAddress WHERE Id IN :lstContactPointAddresses ]);
for(Contact passenger: mapPassengers.values()) {
passenger.MailingStreet = ((Address)mapCPA.get(passenger.Id).Address).Street;
allPassengersToBeUpdated.add(passenger);
}
if (allPassengersToBeUpdated.size() > 0) {
update allPassengersToBeUpdated;
}
}
But still getting the same error