function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Conor Bradley 5Conor Bradley 5 

apex trigger help!!

Hi, we are a publishing company that sell adverts into different magazine 'Issues'(custom SF Object)

I have an apex trigger called EndOfSeriesIssue that takes the latest Issue from opportunityLineItem and puts it to a look up field on opportunity called last_issue__c, based on Issue_publication_date__c

This works fine. However there is a problem when another product is added to the opportunity, which does not contain an issue. Could anyone tell me how to modify my trigger to deal with this problem? Trigger below:
trigger EndOfSeriesIssue on Opportunity (before update) {
    if(trigger.isBefore && trigger.isUpdate) {
        List<OpportunityLineItem> oliList = [SELECT Issue__c, Issue_publication_date__c, OpportunityId FROM OpportunityLineItem WHERE OpportunityId In:trigger.newMap.keySet() ORDER BY Issue_publication_date__c DESC];
        Map<Id, String> oppIdVsLatestIssueMap = new Map<Id, String>();
        if(oliList != null) {
            for(OpportunityLineItem objOLI : oliList) {
                if(!oppIdVsLatestIssueMap.containsKey(objOLI.OpportunityId)) { //Add only one OppId and its Issue which is having latest Issue_publication_date
                    oppIdVsLatestIssueMap.put(objOLI.OpportunityId, objOLI.Issue__c);
                }
            }
            //Updated latest issue to opportunities
            if(!oppIdVsLatestIssueMap.isEmpty()) {
                for(Id filterdOppId : oppIdVsLatestIssueMap.keySet()) {
                    trigger.newMap.get(filterdOppId).last_issue__c = oppIdVsLatestIssueMap.get(filterdOppId);
                }
            }
        }
    }
}
Many Thanks
Conor
Ravi Dutt SharmaRavi Dutt Sharma
Put a check before assigning the value to last_issue__c field. Something like below:
 
//Updated latest issue to opportunities
if(!oppIdVsLatestIssueMap.isEmpty()) {
	for(Id filterdOppId : oppIdVsLatestIssueMap.keySet()) {
		if(oppIdVsLatestIssueMap.get(filterdOppId) != null){
			trigger.newMap.get(filterdOppId).last_issue__c = oppIdVsLatestIssueMap.get(filterdOppId);
		}
	}
}