Skip to content

Instantly share code, notes, and snippets.

@mtetlow
Created February 27, 2014 01:23
Show Gist options
  • Save mtetlow/9242408 to your computer and use it in GitHub Desktop.
Save mtetlow/9242408 to your computer and use it in GitHub Desktop.
//Usage
...stuff
allChildren = trController.stripFLSFields('update', allChildren);
update allChildren;
..morestuff
//Method
public static List<sObject> stripFLSFields(String operation, List<sObject> newRecords){
List<sObject> returnList = new List<sObject>();
if(newRecords.size()>0){
Schema.sObjectType objectType = newRecords[0].getSObjectType();
Map<String,Schema.SObjectField> objectFields = objectType.getDescribe().fields.getMap();
List<Schema.describeFieldResult> flsValidFields = new List<Schema.describeFieldResult>();
for(String fieldKey : objectFields.keySet()){
Schema.SObjectField field = objectFields.get(fieldKey);
Schema.describeFieldResult fieldDescribe = field.getDescribe();
if(operation == 'insert'){
if(fieldDescribe.isCreateable() || fieldDescribe.getName() == 'Id'){
flsValidFields.add(fieldDescribe);
}
} else if(operation == 'update' || operation =='delete'){
if(fieldDescribe.isUpdateable() || fieldDescribe.getName() == 'Id'){
flsValidFields.add(fieldDescribe);
}
} else if(operation == 'upsert'){
if( ( fieldDescribe.isUpdateable() && fieldDescribe.isCreateable() ) || fieldDescribe.getName() == 'Id'){
flsValidFields.add(fieldDescribe);
}
}
}
for(sObject newRecord : newRecords){
sObject objectTemplate = objectType.newSObject();
for(Schema.describeFieldResult field : flsValidFields){
String fieldName = field.getName();
try{
if(newRecord.get(fieldName)!=null){
objectTemplate.put(fieldName,newRecord.get(fieldName));
}
} catch(Exception e){
}
}
returnList.add(objectTemplate);
}
}
return returnList;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment