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
AnsliesdadAnsliesdad 

Help Creating Trigger to Move Account Contacts to Contract Contact Roles

Hi everyone,

I'm a beginner at writing triggers/code and would like to see if anyone can help me finish the trigger below.  When a Contract is created on a given Account, I would like to automatically add that account's Contacts to the related Contract as a Customer Contact Role.  SF provide me some basic code to get started but I'm having a hard time understanding how to customize it for our org.  The trigger is below:

1  /* Adds an Account's related Contacts as Contract Roles to the same Account's related Contracts */
2  
3  trigger AccountContactsToContractRoles on Contract (after insert)
4  {
5      Set<Id>accountIds = new Set<Id>();
6      //To-Do:  Collect account Ids
7      
8      Map<Id, Account> accounts = new Map<Id, Account>([SELECT ID, (SELECT ContactId FROM AccountContactRoles) FROM Account WHERE ID IN :accountIds]);
9      
10      List<ContractContactRole> ccrs = new List<ContractContactRole>();
11      for (Contract c: Trigger.new)
12      {
13          for(AccountContactRole acr : accounts.get(o.AccountId).AccountContactRoles)
14          {
15              ccrs.add(new ContractContactRole(ContractId = o.Id, ContactId = acr.ContactId));
16          }
17      }
18      
19      insert ccrs;
20  }

Thanks to anyone who can help.
@Karanraj@Karanraj
Separate the logics into small pieces then it will be easy to complete the problem. As a first step, you need to get the Account Id from the contract object. You can use the trigger.new which will return the values and you can store it in the list or set the variable.
Set<Id> accountRecordId = new Set<Id>();
for(Contract cc: Trigger.new){
if(cc.accountId != null)
accountRecordId.add(cc.accountId);
 }
Then query the account record along with the contact record using the sub query
Map<Id, Account> accounts = new Map<Id, Account>([SELECT ID, (SELECT Id FROM Contacts) FROMAccount WHERE ID IN : accountRecordId]);
Then instead of AccountContactRole change the into Contacts
List<ContractContactRole> ccrs = new List<ContractContactRole>();
for (Contract c: Trigger.new){
 for(Contact acr : accounts.get(o.AccountId).Contacts)
 {
   ccrs.add(new ContractContactRole(ContractId = c.Id, ContactId = acr.Id));
}
}
if(ccrs.size() > 0)
 insert ccrs;

 
AnsliesdadAnsliesdad
Thanks Karanraj.  I thought I'd replied to you saying "thanks" but I realize I didn't.  Sorry about that and thanks again for your help.