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
Sandile matheSandile mathe 

hi , I am scratching my head here. I want to link link all contacts from the related account that are flagged as key contacts to an opportunity on that account when it is created.

Here are the steps I followed using a trigger but its not happening. Please help. Maybe I am missing something

1. I created a new field of Checkbox type on Contact Object to Flag contact as Key Contact
Field Name : Key_Contact__c
type : Checkbox
Object : Contact


2. The Trigger Class to Link Contacts That Flagged as key Contact when creating an Opportunity.


------------------------------------START------------------------------------------------
trigger LinkContacts on Opportunity (before insert, before update) {
   
set<Id> AccountIds = new set<Id>();
for (Opportunity  o: trigger.new) {
 AccountIds.add(o.AccountId);
}
map<Id, Account> AccountContactMap = new map<Id, Account>();
map<Id, Contact> ContactMap = new map<Id, Contact>();
list<Account> AccConts = new list<Account>();
AccConts = [Select Id, Name, (Select Id, Name, Key_Contact__c from Contacts Where Key_Contact__c = true) from Account where Id IN : AccountIds];
for(Account acc : AccConts){
    AccountContactMap.put(acc.Id, acc);
}

for (Opportunity  o: trigger.new) {
Account Acc = AccountContactMap.get(o.AccountId);
if(Acc != null){
List<Contact> conts = new list<Contact>(Acc.Contacts);
                 map<Id, Contact> ContactMap = new map<Id, Contact>();
                  Contact Con = ContactMap.get(o.ContactId);
if(conts.size() > 0 ){
                   
                    if(Con.Key_Contact__c = true){
                       
                        for(Contact contactFlag : conts){
    ContactMap.put(contactFlag.Id,con );
}
                    }

}
}


}
}

--------------------------------------END-------------------------------------------------

 
Ashish Singh SFDCAshish Singh SFDC
Hello Sandie,

I'm unable to understand your requirement. Would you mind to explain it again with an example.

Thanks,
Ashish Singh.
SarvaniSarvani
Hi Sandile,

Though I didn't understand your requirement, the condition check in your code for key_contact__c should be if(Con.Key_Contact__c == true){ 
== in place of

Thanks
Sandile matheSandile mathe
I will try to break this down maybe with an example. So on the Parent Account you going to have Contacts and Opportunities. So in those contacts there are going to have contcats which are flagged as key contacts(whith Checkbox) and non Key Contacts. So I want to have a trigger in such a way that when you creating an opportunity on a related parent account its just going to link all the contacts which are flagged as key contact(Key_Contact__c == true) . So when you drill into that opportunity I want to see the list of contacts(I can use parent account related list)