Skip to main content
Hi guys, I would asign the old value of "stock_actuel__c" to the new field when a record is created. I develop this trigger. The problem is that when I insert a record I have an exception nullpointer:

MyTigger:

trigger InvoiceStock on Tissus__c (after insert, after update, after delete) {

for(Tissus__c tnew : Trigger.New)

for(Tissus__c told : Trigger.Old){

if(tnew.Name == told.Name)

tnew.stock_actuel__c = told.stock_actuel__c ;

}

}

the Exception:

Error: Invalid Data. 

Review all error messages below to correct your data.

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

 
13 réponses
  1. 8 oct. 2015, 12:21
    Hi Nejib,

    Please try with the below code :

    trigger InvoiceStock on Tissus__c (before insert) {

    Set<String> tissusNameSet = new Set<String>();

    for(Tissus__c tiss : trigger.new){

    tissusNameSet.add(tiss.Name);

    }

    Map<String,Tissus__c> mapOfTissus = new Map<String,Tissus__c>();

    for(Tissus__c tiss : [Select Name,stock_actuel__c from Tissus__c where name In : tissusNameSet]){

    mapOfTissus.put(tiss.Name,tiss);

    }

    for(Tissus__c newTissus : trigger.New){

    if(mapOfTissus.containsKey(newTissus.Name)){

    newTissus.stock_actuel__c = mapOfTissus.get(newTissus.Name).stock_actuel__c ;

    }

    }

    }

    Let me know if you have any issue.

    Thanks,

    Abhishek
0/9000