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
Che SFDCChe SFDC 

System.NullPointerException on Events - Please help!

Dear all, below is my code which automatically send email notificaitons when a new Event is created. If opportunity is not tagged to Event, I`m getting a System.NullpointerException. Could you please help in understanding what I`m doing wrong? I`m new to Apex 

Apex trigger NotifyOnSiteVist2 caused an unexpected exception, contact your administrator: Visitnotify: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.Visitnotify: line 29, column 1

 
Trigger Visitnotify on Event (after insert){
        
    List<Messaging.SingleEmailMessage> newEmails = new List<Messaging.SingleEmailMessage>();
    List<Id> whatIds = new List<Id>();
    List<Id> createdByIds = new List<Id>();
    for(Event e :Trigger.new)
    {
        createdByIds.add(E.CreatedByID);
        whatIds.add(E.whatId);
    }
    Map<Id, User> users = new Map<Id, User>([SELECT Id, Name from User WHERE Id in :createdByIds]);
    Map<Id, Opportunity> opportunities = new Map<Id, Opportunity>([SELECT Name, Account.Name from Opportunity WHERE Id in :whatIds]);
    for(Event e :Trigger.new){
    
    if(e.whatid != NULL){ 
            String fullTaskURL;
            String Facility;
            Datetime startDate;
            Datetime endDate;
            String Purpose;

            
            // Query to populate CreatedBy name in html template
            Id createdByID = E.CreatedByID;
            String createdByName = users.get(createdByID).Name;
                   
            // Query to populate Opportunity name in html template
            String oppID = E.whatId;  
            String oppName = opportunities.get(oppID).Name;
                                 
        if(E.Site_Visit__C ){
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                
            mail.setSubject(' Alert: A New Visit Record is Created');
            mail.setSaveAsActivity(false);
            mail.setTargetObjectId('00580000005LedR'); 
                                     
            fullTaskURL = URL.getSalesforceBaseUrl().toExternalForm() + '/' + E.Id;
            Facility = E.Facility__c;
            startDate = E.StartDateTime;
            endDate = E.EndDateTime;
            Purpose = E.Purpose_of_Visit__c;
                
   
            //Generate email template
                String emailBody;
                emailBody = '<html><body>Hi ,<br> <br> A New Site Visit Record has been created: <a href="' + fullTaskURL + '">' + E.Id + '</a><br></body></html>' + '<br> Sales VP: '+ createdByName + '<br> Opportunity/Account Name: '+ oppName + '<br> <br> Site/Facility: ' + Facility+ '<br> Purpose of Visit: ' + Purpose +  '<br> Start Date/Time: ' + StartDate +  '<br> End Date/Time: ' +endDate +  '<br> <br> Thank you <br> <br> Salesforce Admin' ;
                mail.setHtmlBody(emailBody );

            newEmails.add(mail);
        }
    }

    messaging.sendEmail(newEmails);
} }

 
Best Answer chosen by Che SFDC
Grazitti TeamGrazitti Team
We have updated your code:
Solution: Identify the sObject type of whatID

Trigger Visitnotify on Event (after insert){
        
    List<Messaging.SingleEmailMessage> newEmails = new List<Messaging.SingleEmailMessage>();
    List<Id> whatIds = new List<Id>();
    List<Id> createdByIds = new List<Id>();
    for(Event e :Trigger.new)
    {
        createdByIds.add(E.CreatedByID);
        whatIds.add(E.whatId);
    }
    Map<Id, User> users = new Map<Id, User>([SELECT Id, Name from User WHERE Id in :createdByIds]);
    Map<Id, Opportunity> opportunities = new Map<Id, Opportunity>([SELECT Name, Account.Name from Opportunity WHERE Id in :whatIds]);
    for(Event e :Trigger.new){
    
    if(e.whatid != NULL){
            SObjectType type;
            type = e.whatid.getSObjectType();
            String typee = String.valueOf(type);
            if(typee == 'Opportunity'){

                String fullTaskURL;
                String Facility;
                Datetime startDate;
                Datetime endDate;
                String Purpose;

                
                // Query to populate CreatedBy name in html template
                Id createdByID = E.CreatedByID;
                String createdByName = users.get(createdByID).Name;
                       
                // Query to populate Opportunity name in html template
                String oppID = E.whatId;  
                String oppName = opportunities.get(oppID).Name;
                                     
            if(E.Site_Visit__C ){
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                    
                mail.setSubject(' Alert: A New Visit Record is Created');
                mail.setSaveAsActivity(false);
                mail.setTargetObjectId('00580000005LedR'); 
                                         
                fullTaskURL = URL.getSalesforceBaseUrl().toExternalForm() + '/' + E.Id;
                Facility = E.Facility__c;
                startDate = E.StartDateTime;
                endDate = E.EndDateTime;
                Purpose = E.Purpose_of_Visit__c;
                    
       
                //Generate email template
                    String emailBody;
                    emailBody = '<html><body>Hi ,<br> <br> A New Site Visit Record has been created: <a href="' + fullTaskURL + '">' + E.Id + '</a><br></body></html>' + '<br> Sales VP: '+ createdByName + '<br> Opportunity/Account Name: '+ oppName + '<br> <br> Site/Facility: ' + Facility+ '<br> Purpose of Visit: ' + Purpose +  '<br> Start Date/Time: ' + StartDate +  '<br> End Date/Time: ' +endDate +  '<br> <br> Thank you <br> <br> Salesforce Admin' ;
                    mail.setHtmlBody(emailBody );

                newEmails.add(mail);
            }
        }
    }

    messaging.sendEmail(newEmails);
} }

All Answers

Anoop yadavAnoop yadav
Hi,
This Code looks OK.
Put one debug after line 28 to print the oppId.
I think you have one more trigger, check that also.
Grazitti TeamGrazitti Team
Hi Chetan,

your trigger is working absolutely fine for me.

--
Regards,
Grazitti Team
Web: www.grazitti.com
Email: sfdc@grazitti.com
Che SFDCChe SFDC
Hi Anoop, could you give me an example of debug and how should I add it ? Like I said, i`m new to Apex and I would appriciate if you could give me an example. 
Che SFDCChe SFDC
Hi Grazitti, Tigger creates problem when I try to associate any other record other than Opportunity. It work on with Opportunity. If I create an event and if assign it Account or any other what record, it gives me an error.
Grazitti TeamGrazitti Team
Then it will absolutely generate an error, because in that case what id is not null and also it is not Opportunity id. you understanding?
Che SFDCChe SFDC
Understood, how can i bypass it. I would like my users to associate events to Opportunities as well as Accounts and other What ID`s. Could you please suggest a way?
Grazitti TeamGrazitti Team
We have updated your code:
Solution: Identify the sObject type of whatID

Trigger Visitnotify on Event (after insert){
        
    List<Messaging.SingleEmailMessage> newEmails = new List<Messaging.SingleEmailMessage>();
    List<Id> whatIds = new List<Id>();
    List<Id> createdByIds = new List<Id>();
    for(Event e :Trigger.new)
    {
        createdByIds.add(E.CreatedByID);
        whatIds.add(E.whatId);
    }
    Map<Id, User> users = new Map<Id, User>([SELECT Id, Name from User WHERE Id in :createdByIds]);
    Map<Id, Opportunity> opportunities = new Map<Id, Opportunity>([SELECT Name, Account.Name from Opportunity WHERE Id in :whatIds]);
    for(Event e :Trigger.new){
    
    if(e.whatid != NULL){
            SObjectType type;
            type = e.whatid.getSObjectType();
            String typee = String.valueOf(type);
            if(typee == 'Opportunity'){

                String fullTaskURL;
                String Facility;
                Datetime startDate;
                Datetime endDate;
                String Purpose;

                
                // Query to populate CreatedBy name in html template
                Id createdByID = E.CreatedByID;
                String createdByName = users.get(createdByID).Name;
                       
                // Query to populate Opportunity name in html template
                String oppID = E.whatId;  
                String oppName = opportunities.get(oppID).Name;
                                     
            if(E.Site_Visit__C ){
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                    
                mail.setSubject(' Alert: A New Visit Record is Created');
                mail.setSaveAsActivity(false);
                mail.setTargetObjectId('00580000005LedR'); 
                                         
                fullTaskURL = URL.getSalesforceBaseUrl().toExternalForm() + '/' + E.Id;
                Facility = E.Facility__c;
                startDate = E.StartDateTime;
                endDate = E.EndDateTime;
                Purpose = E.Purpose_of_Visit__c;
                    
       
                //Generate email template
                    String emailBody;
                    emailBody = '<html><body>Hi ,<br> <br> A New Site Visit Record has been created: <a href="' + fullTaskURL + '">' + E.Id + '</a><br></body></html>' + '<br> Sales VP: '+ createdByName + '<br> Opportunity/Account Name: '+ oppName + '<br> <br> Site/Facility: ' + Facility+ '<br> Purpose of Visit: ' + Purpose +  '<br> Start Date/Time: ' + StartDate +  '<br> End Date/Time: ' +endDate +  '<br> <br> Thank you <br> <br> Salesforce Admin' ;
                    mail.setHtmlBody(emailBody );

                newEmails.add(mail);
            }
        }
    }

    messaging.sendEmail(newEmails);
} }
This was selected as the best answer
Che SFDCChe SFDC
Thank you very much Grazitti Team. Much appriciated! 
Grazitti TeamGrazitti Team
Happy to Help :)

--
Regards,
Grazitti Team
Web: www.grazitti.com
Email: sfdc@grazitti.com