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
Bethann GonzalezBethann Gonzalez 

Error-Apex Trigger-UpdateReferrals: execution of AfterInsert caused by: System.NullPointerException

I created a new partner portal. When the partner user creates a new lead and clicks 'save' they recieve the folloing error:


Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger UpdateReferrals caused an unexpected exception, contact your administrator: UpdateReferrals: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.UpdateReferrals: line 33, column 1


This is only occuring with this new partner portal.  I logged in into an old partner portal user and they are able to create and save leads with this error occuring. 


See Apex Trigger. 

trigger UpdateReferrals on Lead (after insert) {

  Set<Id> createdByIds = new Set<Id>();
  List<Id> referralIds = new List<Id>();
  for (Lead l :{
  // Return all users that created Leads in this trigger
  Map<Id, User> creator = new Map<Id, User>([Select Contact.Divisions__c, UserType FROM User WHERE Id IN :CreatedByIds]);
  // Find all of the PowerPartner users who created a Lead in this trigger
  for (Lead l :{
    if (creator.get(l.CreatedById).UserType == 'PowerPartner'){
      referralIds.add (l.Id);
  // Get all of the Leads owned by PowerPartner users discovered above
  List<Lead> referrals = new List<Lead>([SELECT CreatedById, Name, Company, ReplyTo__c FROM Lead WHERE ID in :referralIds]);
  // Loop through all of those Leads
  for (Lead l : referrals){
    // Set the Partner Sales Rep to the creator of the Lead
    l.Partner_Sales_Rep__c = l.CreatedById;
    // Get the divisions of the Partner Sales Rep (From its contact record)
    l.Divisions__c = creator.get(l.CreatedById).Contact.Divisions__c;
    // Set the singular division on the Lead if the Partner only has one division
    if (creator.get(l.CreatedById).Contact.Divisions__c.indexOf(';', 0) == -1){
      l.Division__c = creator.get(l.CreatedById).contact.Divisions__c;

  for (Lead p : referrals){
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    mail.setSubject('Thank you for the referral!');
    mail.setHtmlBody('<p>We will review the referral:</p>'+
    '<p>Contact Name: ' + p.Name + '</br>' +
    '<p>Company Name: ' + p.Company + '</p>' +
    '<p>We will follow-up with you shortly.</p>' +
    '<p>'+ p.ReplyTo__c + '</p>');
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });        
  update referrals;



Bhawani SharmaBhawani Sharma
Change your line# 33 to
if (creator.containsKey(l.CreatedById) && && creator.get(l.CreatedById).Contact.Divisions__c != null && creator.get(l.CreatedById).Contact.Divisions__c.indexOf(';', 0) == -1){