Skip to main content
kali charan ha fatto una domanda in #Apex
Hi everyone,

   I have written the code for contact,and i have the scenario like for the account if the first child is inserted the amount field of contact should be automatically populated to the parent amount field of account and if the next contact is inserted the check box of the account field should be checked and amount is less with the previous contact it should check the check box of lesser amout.

I am getting the error like

Error: Invalid Data. 

Review all error messages below to correct your data.

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

Please fix the issues and if any modifications required.Please help me.

trigger UpdateAmount on Contact (after insert, after update) {

  Map<ID, Account> parentAccs = new Map<ID, Account>(); 

  List<Id> listIds = new List<Id>();

  List<Account> updatedparentAccs = new List<Account>();

  List<contact> COnIds= new List<contact>();

  

   for (contact childObj : Trigger.new) {

    listIds.add(childObj.AccountID);

  }

  parentAccs = new Map<Id, account>([SELECT id, Parent_amount__c,Greater_amount__c,Lesser_Amount__c,Name,(SELECT ID, Amount__c FROM contacts) FROM Account WHERE ID IN :listIds]);

  system.debug('%%%%%%%%%%%'+parentAccs);

  COnIds = [select id,AccountID from contact where AccountID IN :listIds];

  Account myParentOpp;

  

  for (contact con: Trigger.new){

     myParentOpp = parentAccs.get(con.AccountID);

     myParentOpp.Parent_amount__c= con.Amount__c;

     if(COnIds.size()>1 && con.Amount__c>COnIds[0].Amount__c){

     myParentOpp.Greater_Amount__c = true;

     }

     

    updatedparentAccs.add(myParentOpp);

    }

    

  if(!updatedparentAccs.isEmpty()){

  update updatedparentAccs;

  }

}

Thanks.
2 risposte
  1. 10 set 2016, 00:19
    @kali, why you are using "COnIds[0]"? this will always look first contact of that account. And also there is possibility you will get null pointer exception when there is no contact for that account? What is your actual requirment?