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
Harsh GupHarsh Gup 

User is inserted at the parent level Account then add the account sharing records at the child level

Hi Team,

I want to write the trigger for the Scenario,

When Account Team Member inserted/updated into  Account of Level 1
In this case i need the child and grand child of Level 1 account  and add Account sharing records at child and grandchild account.
Best Answer chosen by Harsh Gup
AnudeepAnudeep (Salesforce Developers) 
Hi Harshita, 

This is just a sample code. Please make changes as required
 
trigger insertAccountSharesOnChild on AccountTeamMember(after insert, after update)
{
    List<AccountShare> shares = new List<AccountShare>();
    List<Id> accIds = new List<Id>();
    
	Map<Id, AccountTeamMember> accMap = new Map<Id, AccountTeamMember>();
	for( AccountTeamMember A : Trigger.New )
	{
		if( trigger.isInsert || ( trigger.isUpdate && A.AccountId != trigger.oldMap.get( A.Id ).AccountId ))
			accMap.put( A.AccountId, A );
			accIds.add(A.Id);
    }

//ChildAccounts is the hierarchy account relationship name

   for(Account acc: [Select name,(select id,billingcity from ChildAccounts) from account where Id in:accMap.KeySet()]) {

      for(ChildAccount c:acc.ChildAccounts) {
       AccountShare aShare = new AccountShare();
        aShare.AccountId = c.id;
        aShare.UserOrGroupId = acc.UserId;
        aShare.AccountAccessLevel = 'Edit';
        aShare.ContactAccessLevel = 'Edit';
        aShare.OpportunityAccessLevel = 'Edit';
		shares.add(aShare);
      }
        if( Shares.size() > 0 )
		Insert Shares;
   }
}

If you don't want to use 2 for loops, please see this solution

If you find this code helpful, please mark this answer as best. It may help others in the community. Thank You!

Anudeep