Print this page

Why is AccountId null in my Before Insert/Update Case trigger?

Knowledge Article Number 000221321
Description When you create or edit a Case, you might notice that you cannot access the AccountId in certain scenarios. Below we will go through a reproducible scenario and state the result.
 
  1. First, let’s create a trigger on the Case object that loops through the list of new Cases and write the results to the debug logs:  
    trigger DebugCaseValues on Case (before insert, before update) {
        for(Case c : Trigger.new)
            System.debug('##### Case values: ' + c);
    }
  2. In the Case page layout, the Account and Contact fields are set to Read-Only.
  3. Use two users to test the scenario. So, create one user that has the System Admin and the Standard User profiles.
  4. Set debug logs against both users and complete the following.
  5. Login as each user. Go to an Account, and then go the Case related list and click New Case.
  6. Fill out the required fields and click Save
    • Result: Both users will see something similar to: "##### Case values: Case:{Id=null, ..., AccountId=001..."
  7. Next go to a Contact record, and then go to the Case related list and click New Case. Fill out the required fields and click Save.
    • Results:
      1. System Administrator: "##### Case values: Case:{Id=null, ..., ContactId=003..., AccountId=001..."
      2. Standard User:  "##### Case values: Case:{Id=null, ..., ContactId=003..., AccountId=null, ..."

​​​In the results, we can see that, for the Standard User, the AccountId is returns null in the Before Insert event when both Account and Contact are being assigned on the Case creation.
 
Resolution This result is considered to be working as designed due to the complexity of the implementation of the relationship between the Case, Contact, and Account records.

Because the Account field is Read-Only (as determined either by page layout or field-level security), the AccountId is being reviewed in the database via the Contact record passed resulting in the AccountId being null in the Apex Trigger. Once saved, just before the After Trigger events in the order of execution, the correct Id will be populated.

You can use the following workarounds:
  • For non-administrator users, make the Account field on the Case Object editable (in both field-level security and in the page layout)
  • Move the trigger logic based on the Account Id into the After Trigger events
  • In the Before Insert Trigger, query for the AccountId that is related to the assigned Contact and assign it to the Case.AccountId in the trigger*
*Note: This suggestion is based on standard implementation. The code required might vary depending on your implementation of the Case sObject.




promote demote