🚀Apex Triggers & Ownership Transfer: What Every Dev Should Know🧠

Below are multiple real-world  scenarios covering different versions of how Apex Triggers and user record sharing behave, especially when ownership is changed in various execution contexts:

✅ Scenario 1: Ownership Change via Standard UI 
Context:
- User A is the current owner of a Loan_Application__c object record.
- User B has no access to Loan_Application__c.

Action:
User A tries to assign ownership of the record to User B using Standard UI.

Question:
Will the operation succeed?

Answer:
No, because User B must have at least Read access to the record to become the new owner via the UI.
Error shown: "Before you can transfer this record, the new owner needs Read permission on it and related records."

Scenario 2: Ownership Change via Apex Trigger Called from Class With Sharing
Context:
- An Apex class (defined with with sharing)  updates a Loan_Application__c record.
The record trigger changes the owner to User B.
- User B does not have access to the object.

Question:
Will the trigger successfully change the owner?

Answer:
No, because the trigger inherits the user context from the class using with sharing.
Therefore, Salesforce requires the new owner (User B) to have at least Read access.
Error message:
TRANSFER_REQUIRES_READ, The new owner must have read permission

Scenario 3: Ownership Change via Apex Trigger Called from Class Without Sharing
Context:
- A Loan_Application__c record is updated via an Apex class defined with without sharing.
- This class calls a DML update which invokes a trigger to change the record owner to User B.
- User B has no access to the object.

Question:
Will the ownership change succeed?

Answer:
Yes, because the class is defined with without sharing, so the trigger runs in system mode, and sharing/access checks are bypassed.

Scenario 4: Record Creation with Specific Owner in Anonymous Apex Execution
Context:
- A developer executes code from the Anonymous Window to create a Loan_Application__c record with User B as the owner.
- User B does not have access to the object.

Question:
Will the record creation succeed?
Answer:
Yes, Anonymous window Apex runs in system mode, so the platform does not require the target owner (User B) to have acces.

Happy Learning 😊 


Comments

Popular posts from this blog

🔐 Preventing SOQL Injection in Apex: Secure Your Queries