I'm brand new at SF development but here's what I'm trying to do.
I have a property custom object and it has some basic fields (Address, City, State, Zip). I have a Leasing Invoice custom object as well and when creating that I have a lookup for an associated property. Upon selecting from the lookup, I'd like it to autopopulate the property's address in the Property Address field so that someone can see not only the name of the Property but where it is. This is a picture of my Leasing Invoice form:
I've written the following trigger:
trigger populatePropertyAddress on Leasing_Invoice__c (before insert, before update) {
if(trigger.isbefore && trigger.isinsert){
Set<ID> PropIds = new Set<ID>();
for(Leasing_Invoice__c li : trigger.new)
{
PropIds.add(li.Property__c);
}
list<Property__c> proplist = [SELECT Address__c, id FROM Property__c WHERE id IN:PropIds];
MAP<ID, Property__c> mapProp = new MAP<ID, Property__c>();
for(Property__c p : proplist)
{
mapProp.put(p.id,p);
}
for(Leasing_Invoice__c li : trigger.new)
{
if(trigger.oldmap.get(li.Id).Property__c != li.Property__c){
if(li.Property__c!=null)
{
if(mapProp.containskey(li.Property__c))
{
Property__c p = mapProp.get(li.Property__c);
li.Property_Address__c = p.Address__c;
}
}
else
{
li.Property_Address__c = null;
}
}
} } }
Whenever I try to create a new Leasing Invoice now, whether I populate the Property field or not, I get the error:
"Apex trigger populatePropertyAddress caused an unexpected exception, contact your administrator: populatePropertyAddress: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.populatePropertyAddress: line 23, column 1"
I realize my code is not numbered but for clarity that's this line:
if(trigger.oldmap.get(li.Id).Property__c != li.Property__c){
Can anyone explain what I'm doing wrong?
Thanks so much!
Nick