TransWikia.com

How to update contact object from related junction object?

Salesforce Asked by user42387 on December 25, 2020

I created a junction object called Sponsorship__c and have a many-to-many relationship. It is related to Contact through a master-detail relationship and I have another custom object called Sponsored_Child__c which also has a relationship with Sponsorship__c.

What I need to do is create a trigger that updates a Contact field once a new Sponsorship is been created or updated. That field is Child_Names__c and once a Sponsorship is created, the first name(First_Name__c of Sponsored_Child__c) of the Child is concatenated to the field Child_Names__c of Contact.

One Answer

One of the things I like to do is add formula fields to my Junction objects to simplify things. So the first step would be to make a field on Sponsorship__c; I'll call it: Sponsored_Child_Name__c.

Formula: Sponsored_Child__c.First_Name__c

Another very important thing to keep in mind is bulkification:

Pseudo Code

trigger triggerName on Sponsorship__c (events) {
if (event) { // trigger.isUpdate, trigger.isBefore, etc
Map<Id, Sponsorship__c> contactToSponsorship = new Map<Id, Sponsorship__c>();
Lisit<Contact> contactsToUpdate = new List<Contact>();

for (Sponsorship__c s : trigger.new) {
contactToSponsorship.put(s.contact__c, s);
}

for (Contact c : [SELECT Child_Names__c FROM Contact WHERE Id IN :contactToSponsorship.keySet()]) {
c.Child_Names__c += contactToSponsorship.get(c.Id).Sponsored_Child_Name__c;
contactsToUpdate.add(c);
}

update contactsToUpdate;
}

That should get you close.

Answered by gNerb on December 25, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP