Skip to content

Instantly share code, notes, and snippets.

@JitendraZaa
Last active May 4, 2020 22:54
Show Gist options
  • Save JitendraZaa/3cd6eb71c61781e3e8b9502ba16d235c to your computer and use it in GitHub Desktop.
Save JitendraZaa/3cd6eb71c61781e3e8b9502ba16d235c to your computer and use it in GitHub Desktop.
Apex Based Sharing in Salesforce
trigger Test_Share on Test__c (after insert) {
if(trigger.isInsert){
/**
* Test_Share is the "Share" table that was created when the Organization Wide Default
* sharing setting was set to "Private". Allocate storage for a list of Test_Share
* records.
**/
List<Test_Share> jobShares = new List<Test_Share>();
/** For each of the Test records being inserted, do the following: **/
for(Test__c t : trigger.new){
/** Create a new Test_Share record to be inserted in to the Test_Share table. **/
Test_Share studentRecord = new Test_Share();
/** Populate the Test_Share record with the ID of the record to be shared. **/
studentRecord.ParentId = t.Id;
/** Then, set the ID of user or group being granted access. In this case,
* we're setting the Id of the student__c that was specified by the Test
* Result in the student__c lookup field on the Test record.
**/
studentRecord.UserOrGroupId = t.student__c;
/** Specify that the Student should have edit access for this particular Test record. **/
studentRecord.AccessLevel = 'edit';
/** Specify that the reason the Student can edit the record is because its his test result
* (Student_Access__c is the Apex Sharing Reason that we defined earlier.)
**/
studentRecord.RowCause = Schema.Test_Share.RowCause.Student_Access__c;
/** Add the new Share record to the list of new Share records. **/
jobShares.add(studentRecord);
}
/** Insert all of the newly created Share records and capture save result **/
Database.SaveResult[] jobShareInsertResult = Database.insert(jobShares,false);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment