Reply
Regular Contributor
LessDefined
Posts: 24
0

Please help... Need code to update contact field from custom object.

Please help, I am trying to understand APEX and triggers but for some reason I am rellay struggling.

 

I need to create a field on the contact that looks at the ratings given by the customer on a custom object called Rating. I need it to look at the rating_type__c (picklist) for the type "overall" and to find the most recent rating and display it in the field on the contact called NPS_rating__c. My code (really bad code I tried to adjust from another trigger) is below. And if you could help with one other thing related to this.. I need a field on the account that looks at the NPS_rating__c field on all of the contacts related to that account and gives the median score. Thanks in advance. I will buy you lunch.

 

trigger lastNPSScore on Rating__C(after insert)
{
    // set up lists you will need
    List<Contact> consToUpdate = new List<Contact>();
    Map<Rating_Type__c, NPS_Rating__c> ratingMap = new Map<Rating_Type__c, NPS_Rating__c>();
    
    // go through the list of ratings that were inserted
    for (NPS_Rating__c t: Trigger.New)
    {
        // if they are related to a contact, add the contact id (whoID) and their values to a map
        if (t.WhoId  != null)
        {
            ratingMap.put(t.WhoId, t);
        }
    }
    
    // if the map isnt empty
    if (ratingMap.size() > 0)
    {
        // get all of the contacts related to the rating
        consToUpdate = [SELECT Id, NPS_Rating__c FROM Contact WHERE Rating_Type__c="overall" IN: ratingMap.keySet()];
        // go through the list for each contact
        for (Contact c: consToUpdate)
        {
            // set the last person worked field to the owner of the task
            c.NPS_Rating__c = ratingMap.get(c.Rating_Type__c).Rating_Type__c;
        }
        
        // if the list of contacts isnt empty, update them
        if (consToUpdate.size() > 0)
        {
            update consToUpdate;
        }
    }
}

Trusted Contributor
JBabu
Posts: 380
0

Re: Please help... Need code to update contact field from custom object.

Hi,

 

As per my understanding the map

 

Map<Rating_Type__c, NPS_Rating__c> ratingMap = new Map<Rating_Type__c, NPS_Rating__c>();

 

needs to be changed to 

 

Map<String, NPS_Rating__c> ratingMap = new Map<String, NPS_Rating__c>();

 

If NPS_Rating__c  is a text/number field.