I create a map of Custom Settings and then try to add a new one to it. But it throws the error
AssignByLeadSource: execution of BeforeInsert caused by: System.FinalException: Collection is read-only: External entry point
Here is the code. I removed the offending line counters.put(record.LeadSource, happydog);
and tested everything else and found no errors, works great.
trigger AssignByLeadSource on Lead (before insert) {
// Use row locks to prevent race conditions
{
LeadSourceCounters__c[] temp = [SELECT Id FROM LeadSourceCounters__c FOR UPDATE];
//LeadSourceCounters is a custom setting
}
Map<String, LeadSourceCounters__c> counters = LeadSourceCounters__c.getAll();
//counters is a new map that pulls in all the counts from the custom setting.
System.debug('LeadSourceCounters__c.getAll() = ' + LeadSourceCounters__c.getAll());
System.debug(counters);
for(Lead record: Trigger.new) {
if(record.LeadSource==null) {
//if LeadSource is null, we can't round robin it specially, so continue ends for loop.
continue;
}
if(!counters.containsKey(record.LeadSource)) {
//if LeadSource doesn't exist, adds it and sets value to zero.
LeadSourceCounters__c happydog = new LeadSourceCounters__c(
Name=record.LeadSource,
Value__c=0
);
counters.put(record.LeadSource, happydog);
//put(name in map, map data is leadsourcecounter data with Name and Value)
}
counters.get(record.LeadSource).Value__c+=1;
//add 1 to Value__c counter for that lead source
record.AssignmentId__c = counters.get(record.LeadSource).Value__c;
}
upsert counters.values();
//saves the updated counter for that lead source
}
I was under the impression that maps were mutable, and I could add items to them? Are there exceptions to this? How can I add a new Custom Setting to the map?