+1 vote
31 views
by (163k points)

I have a trigger which creates new Cust_Alert_record when Policy__c record is updated.

Below is my trigger:

trigger AlertTextforContact on Policy__c (after update) {
    List<Cust_Alert__c> CustAlertList = new List<Cust_Alert__c>();

    for(Policy__c pol : trigger.new) {
        if(pol.Account_Role__r.role_name__c.contains('Duplicate') || pol.Account_Role__r.role_name__c.contains('Original')) {
            
            Cust_Alert__c custalert = new Cust_Alert__c(
                Contact__c = pol.Account_Role__r.Contact__c,
                Status__c = 'Active'
            );
            CustAlertList.add(custalert);
        }
    }

    insert CustAlertList;
}

I have two issues with my code above

  1. From line 5 (if statement) which checks for given Duplicate and Original keywords, I am getting Null pointer exception error even though Account_role__r.role_name__c has the given values.
  2. From line 8, Account_Role__r.Contact__c id not getting updated to Contact__c field. Account_Role__c is the parent and Account_Role__r.Contact__c is the grandparent of the Policy__c record.

Can anyone please suggest any changes to the above code so that I can get this done. Thanks!

1 Answer

+1 vote
by (163k points)
 
Best answer

Trigger.new does not contain the parent field values and you are trying to access directly from it. This is the reason you are getting the null pointer exception while using with contains method.

You need to modify the code in such a way that you can access the parent field values. The approach is:-

  1. Create a set to store the Account_Role__c id by running a for loop on trigger.new.

  2. Then query the Account Role object record in a map.

  3. You can access the parent field value from map inside the loop.

     trigger AlertTextforContact on Policy__c (after update) {
     List<Cust_Alert__c> CustAlertList = new List<Cust_Alert__c>();
    
    
    set<Id> accountRoleId = new set<id>();
    for(Policy__c pol : trigger.new) {
        if(pol.Account_Role__c!=null) {
            accountRoleId.add(pol.Account_Role__c);
        }
    }
    Map<id,Account_Role__c> mapOfIdWithAccountRole = new Map<id,Account_Role__c>([select role_name__c,Contact__c from Account_Role__c where id=:accountRoleId]);
    
    for(Policy__c pol : trigger.new) {
        if(mapOfIdWithAccountRole.get(pol.Account_Role__c)?.role_name__c?.contains('Duplicate') || mapOfIdWithAccountRole.get(pol.Account_Role__c)?.role_name__c?..contains('Original')) {
    
            Cust_Alert__c custalert = new Cust_Alert__c(
                Contact__c = mapOfIdWithAccountRole.get(pol.Account_Role__c)?.Contact__c,
                Status__c = 'Active'
            );
            CustAlertList.add(custalert);
        }
    }
    
    insert CustAlertList;
    }
    
Welcome to Memory Exceeded, where you can ask questions and receive answers from other members of the community.
...