0
  trigger StudentInsert on Student__c(before insert) {
       set<ID> classIds=new set<ID>();
    for(Student__c s:trigger.new){
     classIds.add(s.Class__c);
       }
           List<class__c> cls = [select NumberOfStudents__c,MaxSize__c,Class_Id__c from class__c where Class_Id__c IN :classIds];
           Map<Id,Class__c> classMap = new Map<Id,Class__c>();
         for(class__c c :cls){
             if(!classMap.containsKey(c.Class_Id__c)) {
                  classMap.put(c.Class_Id__c,c);
             }
         }
        for(student__c s1 : trigger.new){
         if(classMap.get(s1.class__c).NumberOfStudents__c > classMap.get(s1.class__c).MaxSize__c) {
                 s1.addError('Cannot insert Record - Class is full');
           }
     } 
    update classMap.values();
  }

my student max size is 5,whuile am adding 5 th record in class am getting error like

StudentInsert: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.StudentInsert: line 14, column 1

please help to resolve

1 Answer 1

1

I guess there is either null value in student Class__c field or there is no class with matching Class_Id__c value. And since there is no check if map does contain such key null pointer is thrown.

please change last loop this to:

for(student__c s1 : trigger.new){

            if(!classMap.containsKey(s1.class__c)){
                throw new Exception('there is no class for key "' + s1.class__c +'"');
            }

            Class__c tempClass = classMap.get(s1.class__c);

            if(tempClass.NumberOfStudents__c > tempClass.MaxSize__c){
                s1.addError('Cannot insert Record - Class is full');
            }
        }
3
  • but still its showing same error.....
    – user30881
    Commented Apr 21, 2016 at 8:07
  • can you please give us line? and error message? Commented Apr 21, 2016 at 8:15
  • in below line am getting error if(classMap.get(s1.class__c).NumberOfStudents__c > classMap.get(s1.class__c).MaxSize__c) { s1.addError('Cannot insert Record - Class is full'); } } error:System.NullPointerException: Attempt to de-reference a null object: Trigger.StudentInsert
    – user30881
    Commented Apr 21, 2016 at 9:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .