The ask is a field has to be created on Account and that should show the count of contact records for that specific Account.
In a way we need to create Roll-Up summary functionality between Account and Contact.
It's a famous interview question, isn't it!
Let me break it down.
- When a new contact record is created the count field on the parent Account should be updated.
- When the contact is updated and if the AccountId field is modified to some other Account then we need to update the count field on the Account object.
- When a contact is deleted the count field on the parent Account should be updated as well.
- Last, when the contact is undeleted the count filed on tha parent Account has to be updated as well.
Here is the Trigger to implement it, am using Trigger handler design pattern so the Trigger itself is going to be lean and the handler class is going to have the business logic.
Let me you if you have any better way or refactored way of doing it!