I am trying to get this trigger to work but it is giving me an error and I am not able to figure out why. The error I am getting is "attempt to de-reference a null object)
Why trigger? We have a Destinations object which is linked to Supplier products object via a lookup relationship. There are two types of supplier products(marketplace and curated) We want to count the number of live Supplier products and put them in a separate fields(live counts for each type).
I have gotten so far to actually count the number of live products and it is giving me an error. Can any one help? I am posting the code below
Trigger code :
trigger NoOfLiveProducts on Supplier_Product__c (after insert, after Delete, after update, after undelete) {
set<string> destinationids = new set<string>();
if(trigger.isInsert) {
for(Supplier_product__c products : Trigger.new) {
destinationids.add(products.Destination__c);
}
} else if(trigger.isDelete) {
for(Supplier_product__c products : Trigger.old) {
destinationids.add(products.Destination__c);
}
}else if(trigger.isUnDelete) {
for(Supplier_product__c products : Trigger.new){
destinationids.add(products.Destination__c);
}
} else if(trigger.isUpdate) {
for(Supplier_product__c products : Trigger.new) {
destinationids.add(products.Destination__c);
}
}
if(destinationids.size() > 0){
Productcounter pc = new Productcounter();
pc.updateproductCount(destinationids);
}
}
Class code :
public class Productcounter {
public void updateproductcount(set<string> productIDs) {
if(productIDs == null){
return;
}
if(productIDs.size() == 0){
return;
}
list<Supplier_Product__c> ProductList = new list<Supplier_Product__c>();
ProductList = [Select ID,Destination__c
From Supplier_Product__c
Where Destination__c = :productIDs];
integer totalCount;
map<string, integer> DestinationIDToProductCountMap = new map<string, integer>();
for(Supplier_product__c ProductItem : ProductList){
if(DestinationIDToProductCountMap.containsKey(ProductItem.Destination__c)){
totalCount = DestinationIDToProductCountMap.get(ProductItem.Destination__c);
}else{
totalCount = 0;
}
totalCount += 1;
DestinationIDToProductCountMap.put(ProductItem.Destination__c, totalCount);
}
list<Destination__c> DestinationUpdateList = new list<Destination__c>();
Destination__c DestinationTemp;
for(string ProductID : DestinationIDToProductCountMap.keySet()){
DestinationTemp.ID = ProductID;
DestinationTemp.No_of_Live_Curated_Products__c = DestinationIDToProductCountMap.get(ProductID);
DestinationUpdateList.add(DestinationTemp);
}
if(DestinationUpdateList.size() > 0){
update DestinationUpdateList;
}
}
}