The clearOutRecords would iterate all the fields passed as the currentRecord, then:
1. Exclude the fields as part of the fieldsToExcludeForClearOut Set and relationship fields
2. Check if the field is not null and updateable
3. Special logic to set fields to predefined values
4. Set all other fields to null
5. Return the SObject with fields as null
private static Set<String> fieldsToExcludeForClearOut = new Set<String>{'Cases', 'DoNotCall', 'HasOptedOutOfFax', 'HasOptedOutOfEmail', 'LastName', 'FirstName', 'Email', 'AccountId', 'CreatedDate', 'IsDeleted','Interval__c','OwnerId', 'OtherGeocodeAccuracy','MailingGeocodeAccuracy', 'BillingGeocodeAccuracy','ShippingGeocodeAccuracy'}; public SObject clearOutRecords(SObject currentRecord, String sObjectName){ SObjectType objToken = Schema.getGlobalDescribe().get(sObjectName); DescribeSObjectResult objDef = objToken.getDescribe(); Map<String, SObjectField> fieldsSobject = objDef.fields.getMap(); Map<String, Object> fields = currentRecord.getPopulatedFieldsAsMap(); Type classType = Type.forName(sObjectName); SObject mergedRecord = (SObject)JSON.deserialize('{}', classType); for (String field : fields.keySet()){ if (!fieldsToExcludeForClearOut.contains(field) && !field.contains('__r')){ if (currentRecord.get(field)!=null && fieldsSobject.get(field).getDescribe().isUpdateable()){ if ('User_Status__c'.equals(field)){ mergedRecord.put(field, 'Incomplete'); } else if ('Is_Mail_Same_As_Home__c'.equals(field)){ mergedRecord.put(field, false); } else { mergedRecord.put(field, null); } } else if ('Id'.equals(field)){ mergedRecord.put(field, currentRecord.get(field)); } } } return mergedRecord; }
Initializing the clearOutRecords method
1. Query the fields that you would like to clear
2. Pass the Object to the clearOutRecords method
Contact queryContact = [Select Id, FirstName, LastName, Email, Birthdate, MailingState, Age__c from Contact where MailingState!=null limit 1 ]; Contact clearedOutContact = (Contact)App_Service.instance.clearOutRecords(queryContact, 'Contact');
Output
Contact:{Id=0036300000TQZIwAAP, Birthdate=null, MailingState=null}