0

Is there a way to continue editing an account after using the update DML statement? I keep getting the error: "attempt to dereference a null object". The reason that I am trying to update the account twice is because I need a formula field to populate in order to use the field value.

for (Account acc : [SELECT Id, Name FROM Account WHERE Id = :eventId LIMIT 1])
    {   
        acc.Property__c = propertyId;
        acc.HST__c = acc.Subtotal_2__c * 0.13;
        acc.Payment_Total__c = acc.Subtotal_2__c + acc.HST__c;

        update acc;  //UPDATE ACCOUNT FIRST TIME (should populate formula field)

        acc.Investor_Payout__c = (((acc.New_Payment_Recieved__c + acc.Investor_Payout_Adjustment__c) / 1.13) - acc.Investor_Cleaning_Deduction_Paid__c) * (acc.Investor_Split__c / 100);

        update acc; //UPDATE SECOND TIME

1 Answer 1

3

Formulas don't automatically update in memory, so you have to query the data back from the database first:

Account acc = [SELECT Name FROM Account WHERE Id = :eventId];
acc.Property__c = propertyId;
acc.HST__c = acc.Subtotal_2__c * 0.13;
acc.Payment_Total__c = acc.Subtotal_2__c + acc.HST__c;
update acc;
acc = [SELECT New_Payment_Recieved__c, Investor_Payout_Adjustment__c, Investor_Cleaning_Deduction_Paid__c, Investor_Split__c FROM Account WHERE Id = :eventId];
acc.Investor_Payout__c = (((acc.New_Payment_Recieved__c + acc.Investor_Payout_Adjustment__c) / 1.13) - acc.Investor_Cleaning_Deduction_Paid__c) * (acc.Investor_Split__c / 100);
update acc;

If you have many records to update, do so in bulk to avoid excessive query and DML statements:

Account[] accounts = [SELECT ... FROM Account ...];
for(Account record: accounts) {
    // Processing part 1
}
update accounts;
accounts = [SELECT ... FROM Account ...];
for(Account record: accounts) {
    // Processing part 2
}
4
  • Is this an acceptable time to be doing a SOQL query within a for loop? Oct 5, 2015 at 19:47
  • 2
    @AlexBrigham - Absolutely NOT - There is no acceptable time . Store them in a collection, then run another processing loop
    – Eric
    Oct 5, 2015 at 19:49
  • @AlexBrigham To clarify-- if you're literally just editing one record at a time, as you were in your code, there wouldn't be a "in the loop" scenario. Inside a trigger, you'd want to use a collection to update the accounts twice, querying all of them only once after the first update and before the second round of processing.
    – sfdcfox
    Oct 5, 2015 at 19:54
  • @AlexBrigham I've added an example of how you'd bulkify a simple transaction like this, all you need to do is fill in the blanks.
    – sfdcfox
    Oct 5, 2015 at 19:56

You must log in to answer this question.

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