You need to sign in to do that
Don't have an account?
System.FinalException: Collection is read-only..... Map<String, Schema.SObjectField>
I am getting this error when this method is run.Specifically the remove(). I tried deepcloning a copy, and removing that. Doesn't work. Any solutions ???
System.FinalException: Collection is read-only
private void createExcludeList(){
Map<String, Schema.SObjectField> fieldmap1 = Schema.SObjectType.Account.fields.getMap();
List<String> fieldExcludeList = new List<String> {
'LastModifiedDate', 'LastActivityDate', 'SystemModstamp'};
for(integer i=0; i<(fieldmap1.size()-fieldExcludeList.size()); i++)
fieldmap1.remove(fieldExcludeList[i]); //LINE THAT IS CAUSING THE ERROR
}
Rather than removing, you might try adding to a list. In other words, loop over the map and add to a new map that doesn't include those fields.
Map<String, Schema.SObjectField> fieldmap = new Map<String, Schema.SObjectField>();
Set<String> fieldExcludeList = new Set<String>{'LastModifiedDate', 'LastActivityDate', 'SystemModstamp'};
for(Schema.SObjectField F : Schema.SObjectType.Account.fields.getMap().values()) {
if (!fieldExcludeList.contains(F.getDescribe().getName())) {
fieldmap.put(f.getDescribe().getName(), F);
}
}
All Answers
Rather than removing, you might try adding to a list. In other words, loop over the map and add to a new map that doesn't include those fields.
Map<String, Schema.SObjectField> fieldmap = new Map<String, Schema.SObjectField>();
Set<String> fieldExcludeList = new Set<String>{'LastModifiedDate', 'LastActivityDate', 'SystemModstamp'};
for(Schema.SObjectField F : Schema.SObjectType.Account.fields.getMap().values()) {
if (!fieldExcludeList.contains(F.getDescribe().getName())) {
fieldmap.put(f.getDescribe().getName(), F);
}
}
Thanks. Haven't tried if it works, but I know there is know contains method on lists.
Also do you have any idea why this is write protected?
I tested the above snippet in the system log and it seems to get the job done.
I don't have a clue why it's write protected. The best guess I could give is that it's making a reference to the Schema map rather than a copy. Total speculation, though.
p.s. I switched to a Set instead of a List. That's why the contains method is there.
Thanks for the Ultra Quick response, :smileyvery-happy: I went the same route with sets and it worked.
Also here is a way to do less 'describes' if that matters to you.
private void createExcludeList(){
Map<String, Schema.SObjectField> tempMap = Schema.SObjectType.Account.fields.getMap();
Set<String> fieldExcludeList = new Set<String> {
'lastModifiedDate', 'LastActivityDate', 'SystemModstamp' };
for (String fieldname: tempMap.keySet()){
if(!fieldExcludeList.contains(fieldname))
fieldmap.put(fieldname, tempMap.get(fieldname));
}
}