You need to sign in to do that
Don't have an account?
Ansliesdad
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.
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
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.
Then query the account record along with the contact record using the sub query
Then instead of AccountContactRole change the into Contacts
Ansliesdad
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.