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
Salesforce seekarSalesforce seekar 

Apex sharing ----- via Trigger

hi All , 

I have a custom object called subscription ( sub__c )  . owd for sub__c is public read/write for internal users (salesforce license) and private for external users (portal users ----> if we create a contact under account and click on button manage external user  , who are normally called partner users   ). partner users login via partner portal . 

Issue : in my account a1 ,  if i have contacts c1 and c2 now and they are converted as partner users . if i made a opportunity under account a1 to closed won i will get a subscription s1  created  under related list of  a1 ,  as c1 and c2 are created before subscription is created they are able to see the subscription under the related list . 

if a new contact c3 is created  , and now it is made  as portal user under the same account a1 , he is unable to see the subscription record . sharing of the s1 record is not happening  for new created contacts . so i wrote a below trigger on contact , please guide me is this approach correct . 

trigger : 

trigger ContactShare on contact (after update,after insert)
if(trigger.isAfter && trigger.isInsert){
   List<Subscription__Share> shares = new List<Subscription__Share>();
   for(Contact c :{
     for(Sub__c sb: [select id from Sub__c where AccountOwnerId__c = :c.accountid]){
       System.debug('sb Details*****'+c);
       Subscription__Share sr = new Subscription__Share();
       sr.UserOrGroupId =;
       sr.parentId =;
       sr.AccessLevel = 'Read';
       System.debug('shares Details*****'+shares);
   if(shares.size() >0) insert shares;

To acheive : I want to acheive that  everytime if a new contact is created ,  subscription s1 which is present below a1 need to be visible below the related list for that contact , if the partner users login via partner portal .   
write a sharing Rule.
Salesforce seekarSalesforce seekar
@amul : sharing rule on which one , can you eloborate or give me the example where to write
I am hoping Those contact are also user. And these user has some Role it. So write rule based on user's assigned Role.