Tag Archives: Sharing Rule

Salesforce Generic Sharing Record Using sObject

Sample Code:

//Create sharing object for the custom object Student
Schema.SObjectType stdShareType = Schema.getGlobalDescribe().get('Student__Share');
SObject stdShare = stdShareType.newSObject();
stdShare.put('ParentId', 'a0E0I00000fFSUBUA4'); //Set the ID of record being shared
stdShare.put('UserOrGroupId', UserInfo.getUserId()); //Set the ID of User or Group or Territory being granted access
stdShare.put('AccessLevel', 'Read'); //Set the Account access level
stdShare.put('RowCause', 'Student__c'); //Set the Row Cause reason
Database.SaveResult sr = Database.Insert(stdShare,false);

Salesforce Sharing Record Using Apex

For Custom Object:

//Create sharing object for the custom object Student
Student__Share studentShare  = new Student__Share();
studentShare.ParentId = recordId; //Set the ID of record being shared
studentShare.UserOrGroupId = userOrGroupId; //Set the ID of User or Group or Territory being granted access
studentShare.AccessLevel = 'Edit'; //Set the access level
Database.SaveResult sr = Database.Insert(studentShare,false);

For Standard Object:

//Create sharing object for the Standard object Account
AccountShare accshare = new AccountShare();
accshare.AccountId = accountId; //Set the Account ID of record being shared
accshare.UserOrGroupId = userOrGroupId; //Set the ID of User or Group or Territory being granted access
accshare.AccountAccessLevel = 'Edit'; //Set the Account access level
accshare.ContactAccessLevel = 'Edit'; //Set the Contact access level
accshare.OpportunityAccessLevel = 'Edit'; //Set the Opportunity access level
Database.SaveResult sr = Database.Insert(accshare,false);