I tried this by using this inserting, updating employee record. My task is if employee test__c is equal to contact__c test__c employee is automatically created as that contact child if no contact with that test__c value update null in employee.

It's working when we insert or update in salesforce Ui. If I try in data loader I get this error:

CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY:fillValueInChild: execution of beforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.fillValueInChild: line 13, column 1

trigger fillValueInChild on Employee__c (before insert, before update) {

    Map<decimal,Contact> valsFound = New Map<decimal,Contact>();

    for(employee__c emp : trigger.new){
        for(Contact c : [select id,test__c from contact where test__c =:emp.test__c]) {

    for(employee__c emp : trigger.new) {

        if(valsFound.size()>0) {
            emp.contact__c = valsFound.get(emp.test__c).id;
        } else {
            emp.test__c = null;
            emp.contact__c = null;

First: you are asking how to write trigger for bulk records and you have a query in a loop. That's a really bad practice and is certainly NOT bulkified. Read about it here(Best Practice #2)

Second: your problem arises on this line:

emp.contact__c = valsFound.get(emp.test__c).id;

Reason being that if you try to get something from a map with a key that doesn't exist in a map you will get null back. And calling .id on null results in Attempt to de-reference a null object. A possible way to fix it would be adding a check that this key exists:

if(valsFound.size()>0 && valsFound.containsKey(emp.test__c)) {
    emp.contact__c = valsFound.get(emp.test__c).id;
} else {
  • The size check adds absolutely nothing here. Otherwise nice answer. +1 for containsKey. – Adrian Larson Jan 11 '16 at 16:12
  • @AdrianLarson yes, you're right. I just copied and extended OPs code – Novarg Jan 11 '16 at 16:15
emp.contact__c = valsFound.get(emp.test__c).id;

this line is problematic. valsFound.get(emp.test__c) returns null so it becomes null.id and this throws attempt to de-reference null object error

you should change it like this;

if(valsFound.get(emp.test__c) != null) emp.contact__c = valsFound.get(emp.test__c).id;
  • hi i tried but while save code showing error in this statement if(valsFound(emp.test__c) != null) error:Method does not exist or incorrect signature: valsFound(Decimal) at line 12 column 8 – user123 Jan 11 '16 at 14:54
  • I've fixed it. Try it again please. – tugce Jan 11 '16 at 14:58
  • yes its working but records updating when we update in salesforce ui if i used dataloader records not updating test__C field i need to update bulk records using data loader – user123 Jan 11 '16 at 15:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.