Take the 2-minute tour ×
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.

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
testvalues.add(1);
testvalues.add(6);
testvalues.add(2);
testvalues.add(8);
testvalues.add(7);
testvalues.add(2);

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
testvalues.sort();

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

system.debug('the median is: '+median);
share|improve this question

1 Answer 1

  1. download eclipse (if you don't already have it) http://wiki.developerforce.com/page/Force.com_IDE_Installation
  2. create a sandbox (if it doesn't exist)

     https://na<your environment number>.salesforce.com/07E?retURL=%2Fui%2Fsetup%2FSetup%3Fsetupid%3DDataManagement&setupid=DataManagementCreateTestInstance
    
  3. create the sandbox project in eclipse by adding a force.com 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 : trigger.new){
            <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 trigger.new list and it will reflect your customization. You also need to create an Apex class that tests the trigger (for code coverage)

 class NPSSCore {
     @IsTest
     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 = :contact.id];
         system.assertEquals(5, contact.Median_NPS_Score__c);
     }
}

Deploy both the class and the trigger to production by selecting both files and selecting Force.com ->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

 
discard

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.