+ Start a Discussion
Rahul GoyalRahul Goyal 

Trigger to update custom setting

Hi All,

I have a trigger which will update Custom setting value. Whenever we are inserting records the count field on the custom setting will increment by that no of records, so if the current custom setting value is 1 and if I am inserting 10 records using dataloader, count will increment to 11 in custom setting. currently my code is working fine if I am trying to insert records manually one by one, but If I insert bulk load through dataloader, count is increment by 1 only. Please check my code and let me know what I am missing.

trigger newTrigger on TestApp__c (after insert) {
        List<TestApp__c> newTest = new List<TestApp__c>();
    Integer CountNumber;
//updateCount__c is custom setting
     List<updateCount__c> mcs = new  List<updateCount__c>();
     mcs = updateCount__c.getall().values();
    countNumber = Integer.valueof(mcs[0].count__c); //count__c is custom setting field where I am storing count of the records.
    for(TestApp__c test:Trigger.new)
             System.Debug('$$$$$$$$' +mcs[0].count__c);
            mcs[0].count__c = countNumber+1;
    System.Debug('$$$$$$$$' +mcs[0].count__c);
 update mcs;
James LoghryJames Loghry
Since you assign countNumber outside of your loop, you're incremementing the same number by 1 over and over and over again.  Say the old value of your field was 5.  Your loop would set count__c = 5 + 1; up to 200 times.

Instead, you can do one of two things:
  • Remove the loop and just set mcs[0].count__c = Trigger.new.size();
  • Keep the loop and update mcs[0].count__c = countNumber+1 to mcs[0].count__c++;