I have a trigger which is creating a record on an object (Profile__c) when a record is created on another object (Role__c). Now there is no lookup to Contact directly on both the objects. So I'm referencing Contact through other related objects. My trigger is getting saved, however it is not creating records in Profile__c object. When Im adding a new record in Role__c, its giving error : "Attempt to de-reference a null object: on line v.Finance__r.Client_Id__r.Contact__c = o.Finance__r.Client_Id__r.Contact__c;
" Please suggest.
Trigger:
trigger createprofile on Role__c(after insert) {
List <Profile__c> profileToInsert = new List <Profile__c>();
List<Profile__c> profile = [SELECT Asset__c, Finance__c, Quantity__c, Finance__r.Client_Id__r.Contact__c FROM Profile__c];
for (Role__c o : Trigger.new) {
Integer i = 0;
Profile__c existingPos;
for (Profile__c currentPos : profile) {
if (o.Asset_Id__c == currentPos.Asset__c
&& o.Finance__r.Client_Id__r.Contact__c == currentPos.Finance__r.Client_Id__r.Contact__c
&& o.Finance__c == currentPos.Finance__c){
i = 1;
existingPos = currentPos;
break;
}
}
if (i != 1) {
if (o.Finance__c != null) {
if (o.Order_Type__c != 'Sell') {
Profile__c v = new Profile__c ();
v.Finance__r.Client_Id__r.Contact__c = o.Finance__r.Client_Id__r.Contact__c;
v.Asset__c = o.Asset_Id__c;
v.Quantity__c = o.Quantity__c;
v.Finance__c = o.Finance__c;
profileToInsert.add(v);
} else {
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR, 'Add Buy first');
ApexPages.addMessage(myMsg);
}
}
try {
insert profileToInsert;
} catch (system.Dmlexception e) {
system.debug (e);
}
} else {
if (o.Order_Type__c == 'Buy') {
existingPos.Quantity__c = existingPos.Quantity__c + o.Quantity__c;
} else {
existingPos.Quantity__c = existingPos.Quantity__c - o.Quantity__c;
}
update existingPos;
}
}
}