function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
AjazAjaz 

Records sharing using Apex - [Records are inserted successfully but do not reflect in __share table]

Today I have encountered a wierd problem while sharing the records through Apex. Appreciate if someone can help me understand the root cause or faced the similar issue earlier.

Flow of the Code is :
Trigger -> Apex Controller

Objects =>
1. CustomObject__c [ lookup to Account ]
2. AccountTeam__c [ Custom Object having a lookup to Account, It behave like standard AccountTeamMember Object but is a custom defined. This contains all the TeamMembers to a particular Account]

The idea is to share CustomObject__c records (After Insert) with the referred Account.

Below is the code :

TRIGGER
trigger createSharingTrigger on CustomObj__c (after insert) {

  list <CustomObj__c >  recordsList = new list<CustomObj__c > ();
  // Below controller has the logic to share records with Team Members
  sharingRuleController SRObj = new sharingRuleController();

  if (Trigger.isInsert){
    for(CustomObj__c  rec : trigger.new){
    recordsList.add(rec);
    }
   
    if (!recordsList.isEmpty()) {
       SRObj.createSharingRecords(recordsList);
    }
  }
}

APEX Controller :
public without sharing class sharingRuleController
{
    public void createSharingRecords(List<CustomObject__c> shareThisRecords)
      {
         set<Id> accountIdSet = new set<Id>();
         list<CustomObject__Share> shareObjectList = new list<CustomObject__Share>();
    
         for (CustomObject__c cObj: shareThisRecords){
              accountIdSet.add(cObj.Account__c);
          }
    
         list <AccountTeam__c> accTeamMembersList = [select Account__c, TeamMemberID__c, from AccountTeam__c  where Account__c IN :accountIdSet];
     
        for (CustomObject__c cObj: shareThisRecord){

            for (AccountTeam__c TeamMember : accTeamMembersList){
       
                if (TeamMember.Account__c == shareThisRecord.Account__c){
                    CustomObject__Share cShare = new CustomObject__Share();
                    cShare.ParentId = shareThisRecord.Id; // -> This does not show records in Table, although it has same ID value. The ID is generated for sharing record but cannot query the ID, returns no rows.
                        //GAPShare.ParentId = 'a0p17000000NhM9AAK'; -> This Works
                    cShare.UserorGroupId = TeamMember.TeamMemberID__c;
                    cShare.AccessLevel = 'Read';
                    shareObjectList.add(cShare);
                }
            }   
        }

    try{        
             Database.SaveResult[] shareInsertResult = Database.insert(shareObjectList, false);
             system.debug('GAPShareInsertResult => ' + GAPShareInsertResult); -> GetID has an ID value, and isSuccess is "TRUE". But the record when retrieved using the generated ID returns no rows.
    }catch(Exception e){
       // No exceptions thrown either.
       System.debug("Thrown an exception");
    }
}

Really Appreciate if someone can help me identify the issue here. The confusion is that the records are being saved and their respective generated IDs are shown in Debug logs (saveResult[]). And also, if the parentID of the sharedRecord is hardcoded, it works !!!

Thanks in Advance,
Ajaz.
AshlekhAshlekh
Hi,

You need to create "Apex Sharing Reasons" under the CustomObject__c object.
if (TeamMember.Account__c == shareThisRecord.Account__c){
                    CustomObject__Share cShare = new CustomObject__Share();
                    cShare.ParentId = shareThisRecord.Id; 
					// -> This does not show records in Table, although it has same ID value. 
					//The ID is generated for sharing record but cannot query the ID, returns no rows.
                    //GAPShare.ParentId = 'a0p17000000NhM9AAK'; -> This Works
                    cShare.UserorGroupId = TeamMember.TeamMemberID__c;
					cShare.RowCause  = Schema.CustomObject__Share.rowCause._You_need_to_create_Under_the_object_and_put_Here_name
                    cShare.AccessLevel = 'Read';
                    shareObjectList.add(cShare);
                }

https://developer.salesforce.com/page/Using_Apex_Managed_Sharing_to_Create_Custom_Record_Sharing_Logic

-Thanks
Ashlekh Gera
Wei Ding 6Wei Ding 6
Hello you two,
I am also facing the similar problem with apex sharing. Although I set the Apex Sharing Reason in the object.
The object ServicePartnerRequest should be shared by the users in the same partner community.
Here is the code: 
//In Partner Community, I want to share the Service PartnerRecords (private) with the users from the same Community
List<ServicePartnerRequest__Share> sprss = new List<ServicePartnerRequest__Share>();
ServicePartnerRequest__Share sprs = new ServicePartnerRequest__Share();  
ServicePartnerRequest__c spr = [SELECT Id, Internationalsuppliernumber__c FROM ServicePartnerRequest__c WHERE Id = 'a009E000009wgDD'];
String internationalSuppNum = spr.Internationalsuppliernumber__c;
User usr = [SELECT  ContactId, Contact.AccountId, userRoleId FROM User WHERE Contact.Internationalsuppliernumber__c =: internationalSuppNum LIMIT 1];  
Group grp = [Select Id,Name,RelatedId,Type From Group where RelatedId IN (select Id from userRole where Id=:usr.userRoleId) and type='RoleAndSubordinates'];
       	
sprs.ParentId = spr.Id;
sprs.UserOrGroupId = grp.Id;
sprs.AccessLevel = 'All';
sprs.RowCause = Schema.ServicePartnerRequest__Share.RowCause.SameCommunityUsr__c;
sprss.add(sprs);

//System.debug shows the wished result
System.debug('sprs: '+sprs.ParentId+', '+sprs.UserOrGroupId+', '+sprs.RowCause);


try{
    Database.SaveResult[] ls = Database.insert(sprss,false);  
    //inserted without exception, but in the ServicePartnerRequest__Share the insertion is not found
}catch (Exception dmlEx){
			System.debug('Thrown an exception');		
}
The last System.debug output the right result. Insert without exception. But in the share table ServicePartnerRequest__share is the new record not found.