Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a field on the contact called 'NPS Score'. I need a trigger that calculates the median of all contact NPS score's on the account. I have code to calc a median score, I am just not sure how to write the trigger. Someday I need to get to a class!!

List<Integer> testvalues = new List<Integer>();

// Insert some values

Integer sizeOfList = testvalues.size();
system.debug('size of list is '+ sizeOfList);
Integer index = sizeOfList - 1;
system.debug('the index is '+index);
Decimal median = 0.0;

// sort the list first

//Calculate median
if (Math.mod(sizeOfList, 2) == 0) {
   median = (testValues[(index-1)/2] + testValues[(index/2)+1])/2;
   median = testvalues[(index+1)/2];

system.debug('the median is: '+median);
share|improve this question
  1. download eclipse (if you don't already have it)
  2. create a sandbox (if it doesn't exist)

     https://na<your environment number>
  3. create the sandbox project in eclipse by adding a project.
  4. create a trigger called NPSSCore
  5. the creation of the trigger will pop a screen where you can select the object and the event.
  6. choose Contact as the object and "before insert" as the event.

    trigger NPSScore on Contact (before insert) {
         for (Contact contact :{
            <your code>
            contact.Median_NPS_Score__c = median;

There is no need with a before insert to do an update, just modify the object contained within the list and it will reflect your customization. You also need to create an Apex class that tests the trigger (for code coverage)

 class NPSSCore {
     static void test_npsscore(){
         Contact contact = new Contact(firstname='test',lastname='user',npsscore__c=5);
         insert contact;
         contact = [select Median_NPS_Score__c from Contact where id =];
         system.assertEquals(5, contact.Median_NPS_Score__c);

Deploy both the class and the trigger to production by selecting both files and selecting ->Deploy or by using change sets.

share|improve this answer
+1 for starting off with download eclipse and including test code. – Greg Grinberg Jan 23 '13 at 20:42

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.