When an Account’s field Share_With_User__c (a lookup to User) is filled, automatically share that Account with that user via Apex sharing.

146 views

Apex Trigger to When an Account’s field Share_With_User__c (a lookup to User) is filled, automatically share that Account with that user via Apex sharing in Salesforce

To automatically share an Account with a user when a lookup field (Share_With_User__c) is populated, you must use Apex Managed Sharing via an Apex Trigger.

Because the Account is a standard object, Apex sharing is achieved by inserting records into the AccountShare object. This approach requires the Organization-Wide Default (OWD) for Account to be Private or Public Read Only.

👉 Download Free Ebook →

👉 Get Complementary →

right side banner -- www.w3webmart.com

Step 1 Account Trigger (After Update): AccountSharingTrigger.apxt

  1.    TRIGGER AccountSharingTrigger ON Account (after INSERT, after UPDATE) {
  2.     IF (TRIGGER.isAfter) {
  3.         IF (TRIGGER.isInsert || TRIGGER.isUpdate) {
  4.             AccountSharingHelper.shareAccountWithUser(TRIGGER.new, TRIGGER.oldMap);
  5.         }
  6.     }
  7. }

 

 

Step 2 Apex Controller: AccountSharingHelper.apxc

  1.   public class AccountSharingHelper {
  2.     public static void shareAccountWithUser(List<Account> newAccounts, Map<Id, Account> oldAccountMap) {
  3.         List<AccountShare> sharesToCreate = NEW List<AccountShare>();
  4.  
  5.         FOR (Account acc : newAccounts) {
  6.             // CHECK IF USER lookup IS populated AND either NEW OR changed
  7.             IF (acc.Share_With_User__c != NULL && 
  8.                 (oldAccountMap == NULL || acc.Share_With_User__c != oldAccountMap.get(acc.Id).Share_With_User__c)) {
  9.  
  10.                 // Do NOT share WITH the owner (owner already has access)
  11.                 IF (acc.Share_With_User__c != acc.OwnerId) {
  12.                     AccountShare share = NEW AccountShare();
  13.                     share.AccountId = acc.Id;
  14.                     share.UserOrGroupId = acc.Share_With_User__c;
  15.                     share.AccountAccessLevel = 'Edit'; // 'Read' OR 'Edit'
  16.                     share.OpportunityAccessLevel = 'Read'; // Required
  17.                     share.CaseAccessLevel = 'Read'; // Required
  18.                     share.RowCause = 'Manual'; // FOR standard objects, USE 'Manual'
  19.                     sharesToCreate.add(share);
  20.                 }
  21.             }
  22.         }
  23.  
  24.         IF (!sharesToCreate.isEmpty()) {
  25.             DATABASE.insert(sharesToCreate, FALSE); // FALSE allows partial success
  26.         }
  27.     }
  28. }

 

Key Implementation Notes

  • Access Level: AccountAccessLevel can be set to ‘Read’ or ‘Edit’.
  • RowCause: For standard objects, Apex sharing must use Schema.AccountShare.RowCause.Manual (or simply ‘Manual’).
  • Limitations: If the Account owner changes, sharing records with RowCause as ‘Manual’ are automatically deleted.
  • Alternative: For low-code environments, this can be achieved using an After-save Record-Triggered Flow by creating records in the AccountShare object.

 

Approach 2:

Write apex login directly to Apex Trigger

Step 1 Account Trigger (After Update): AccountSharingTriggerr.apxt


🎁 Up to 99% Off Courses (Coupon)
💥 Use Promo Code: STANDARDOFFER💥
🚀 Get Free Salesforce Course Access: www.thevijaykumar.w3web.net

  1. TRIGGER ManualAccountSharing ON Account (after INSERT, after UPDATE) {
  2.  
  3.     List<AccountShare> sharesToInsert = NEW List<AccountShare>();
  4.  
  5.     FOR (Account acc : TRIGGER.new) {
  6.         // CHECK IF Share_With_User__c IS populated
  7.         IF (acc.Share_With_User__c != NULL) {
  8.  
  9.             // CREATE a manual share record
  10.             AccountShare accShare = NEW AccountShare();
  11.  
  12.             accShare.AccountId = acc.Id;
  13.             accShare.UserOrGroupId = acc.Share_With_User__c; // USER TO share WITH
  14.             accShare.AccountAccessLevel = 'Edit'; // OR 'Read'
  15.             accShare.OpportunityAccessLevel = 'None';
  16.             accShare.CaseAccessLevel = 'None';
  17.             accShare.RowCause = Schema.AccountShare.RowCause.Manual; // Manual sharing reason
  18.  
  19.             sharesToInsert.add(accShare);
  20.         }
  21.     }
  22.  
  23.     IF (!sharesToInsert.isEmpty()) {
  24.         INSERT sharesToInsert;
  25.     }
  26. }

 

Further post that would you like to learn in Salesforce

 

FAQ (Frequently Asked Questions)

What is apex-based sharing?

Apex managed sharing enables developers to programmatically manipulate sharing to support their application's behavior through either Apex or SOAP API. This type of sharing is similar to managed sharing. Only users with “Modify All Data” permission can add or change Apex managed sharing on a record.

How to give apex class access to user?

Select a profile, and click its name. In the Apex Class Access page or related list, click Edit. Select the Apex classes that you want to enable from the Available Apex Classes list and click Add. Or select the Apex classes that you want to disable from the Enabled Apex Classes list and click Remove.

Is account sharing allowed on Apex?

Never share your credentials. Sharing your Apex Legends account info means your account could get stolen, and we may decline to restore it.

Related Topics | You May Also Like

👉 Get Complementary →

right side banner -- www.w3webmart.com
 
  
👉 Get Free Course →

📌 Salesforce Administrators

📌 Salesforce Lightning Flow Builder

📌 Salesforce Record Trigger Flow Builder

👉 Get Free Course →

📌 Aura Lightning Framework

📌 Lightning Web Component (LWC)

📌 Rest APIs Integration



Hi, This is Vijay Kumar behind the admin and founder of w3web.net. I am a senior software developer and working in MNC company from more than 8 years. I am great fan of technology, configuration, customization & development. Apart of this, I love to write about Blogging in spare time, Working on Mobile & Web application development, Salesforce lightning, Salesforce LWC and Salesforce Integration development in full time. [Read full bio] | | The Sitemap where you can find all published post on w3web.net