You need to sign in to do that
Don't have an account?

Trigger populate parent record field based on loop through related list values
I am having trouble with how to go about writing a trigger to complete the following:
I have two related objects Contacts and Contact Specialties (related list on Contacts). Any time a Contact Specialty record is added, edited, or deleted from a Contact, I need a trigger to fire that loops through all Contact Specialty records on the Contact and looks to see if the Specialty field on any of the related Contact Specialty records is one of three values: "Family Medicine", "General Medicine", or "Family Practice". If so, I need to check the PCP__c checkbox on the Contact record, if not I need to uncheck the PCP__c checkbox for that contact.
Could anyone be of assistance with this?
I have two related objects Contacts and Contact Specialties (related list on Contacts). Any time a Contact Specialty record is added, edited, or deleted from a Contact, I need a trigger to fire that loops through all Contact Specialty records on the Contact and looks to see if the Specialty field on any of the related Contact Specialty records is one of three values: "Family Medicine", "General Medicine", or "Family Practice". If so, I need to check the PCP__c checkbox on the Contact record, if not I need to uncheck the PCP__c checkbox for that contact.
Could anyone be of assistance with this?
trigger setupPCP on Contact_Speciality__c (after insert, after update, after delete) {
// get the contacts
Set<Id> contactids=new Set<Id>();
Map<Id, Contact_Speciality__c> specMap;
// figure out which map is populated
if (Trigger.isInsert || Trigger.isUpdate)
{
specRecs=Trigger.newMap();
}
else
{
specRecs=Trigger.oldMap();
}
// get the contact ids from the speciaity records
for (Contact_Speciality__c spec : specMap.values)
{
contactIds.add(spec.Contact__c);
}
// now retrieve the contacts and all of their associated specialities, so that we can figure out the correct value for the contact
List<Contact> toUpdate=new List<Contact>();
for (Contact cont : [select id, PCP__c, (select id, Speciality__c from Contact_Specialities__r) from Contact where id in :contactIds])
{
// iterate the specialities looking for speciality values that require the PCP flag to be set on the contact
boolean checkPCP=false;
for (Contact_Speciality__c cSpec : cont.Contact_Specialities__r)
{
if (cSpec.Speciality__c=='Family Medicine' || cSpec.Speciality__c=='General Medicine' | cspec.Speciality__c=='Family_Practice__c')
{
checkPCP=true;
break; // no need to continue with the inner loop as we know we need to check the PCP box on the contact
}
}
// is the result different to the contact record?
if (checkPCP!=cont.PCP__c)
{
cont.PCP__c=checkPCP;
toUpdate.add(cont);
}
}
if (!toUpdate.isEmpty())
{
update toUpdate;
}
}