function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Aviator517Aviator517 

Retrieve object fields and values

For a given record, how could I go about getting all the fields in that object (schema describe?) and back up field specific data for a record. The use case would be, if I deleted a record, could I backup all fields and associated values into a text file or something? Would want it to be scalable so that if I added a new field, I wouldn't have to modify the code everytime.
Ramu_SFDCRamu_SFDC
This is something which is not possible, the only way you can backup would be to run a query by selecting all fields and taking a backup irrespective of whether the field contains data or not.
magicforce9magicforce9
Hi,

I can give you some sample code to begin with...The method in example needs a new instance of sobject to be passed and it will give you the list of accessable fields in that object. The method is very generic so it will work if you add/remove fields from any object.

public with sharing class CustomArchive{

    public List<String> getAllReadableFields(sObject newObj) {
        List<String> fields = new List<String>();
        Map<String, Schema.SobjectField> fieldsMap = newObj.getSObjectType().getDescribe().fields.getMap();
        for (String s : fieldsMap.keySet())
            if (fieldsMap.get(s).getDescribe().isAccessible())
                fields.add(s);
        return fields;
    }
    //Once you the list of fields you can implement your own logic to use them
}

//Example use of the above mehod would be
List<String> getContactFields = CustomArchive.getAllReadableFields(new Contact());

blucasblucas

The code below will give you a SOQL statement with all columns (visible to you). A potential problem here is that there is a limit to the max length of a SOQL statement. Turning the returned data into a text file might be a bit difficult inside Apex/SalesForce. Have you thought about doing this externally? You would have to use the SOAP API since you need the getDeleted and queryAll commands. The REST API doesn't offer queryAll

 String objectName;
SObjectType objectToken;
Map<String, Schema.SObjectField> fieldMap;
List<String> fieldNames;
String soqlStatement;

objectName = 'MyObject__c';

objectToken = Schema.getGlobalDescribe().get(objectName);
fieldMap = objectToken.getDescribe().fields.getMap();

fieldNames = new List<String>();
for (Schema.SObjectField objectField : fieldMap.values())
{
    fieldNames.add (objectField.getDescribe().getName());
}

soqlStatement = 'select ' + String.join (fieldNames,',') + ' from ' + objectName + ' where Id = SOME_ID';