Surely you've had the need to generate a spreadsheet with object and field details for someone to use for a data conversion or integration, right?
I had previously posted a solution involving a Cast Iron orchestration that could go object by object within your org and write to another custom object some details like field name, field data type, length, etc.
Here is another way, that I'll make as a unmanaged package in a future post. In the interim, here is the recipe:
1. Create a custom object to hold the definitions. In the anonymous apex below, my reporting object, ObjDef__c has fields like Object_Name__c, Field_Name__c, Data_Type__c, Length__c.
2. Execute the following anonymous apex for each of the objects you'd like to report on. In my example, I have a custom object called 'Conference__c' that I want to define so that my business partner can create a data dictionary.
****************
//this is the object that you want to define
String type='Conference__c';
map<string, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
Schema.SObjectType mySchema = schemaMap.get(type);
map<string, Schema.SObjectField> fieldMap = mySchema.getDescribe().fields.getMap();
//this is the object that you will report on
list<ObjDef__c> myDefs = new list<ObjDef__c>();
//loop through each of the fields on the object and create a record in your reporting obj
for (String fieldName: fieldMap.keySet())
{
//this is the reporting obj
ObjDef__c myDef = new ObjDef__c();
myDef.Object_Name__c = type;
myDef.Name = fieldName;
myDef.Field_Name__c = string.valueOf(fieldMap.get(fieldName).getDescribe().getLabel());
myDef.Data_Type__c = string.valueOf(fieldMap.get(fieldName).getDescribe().getType());
myDef.Length__c = Integer.valueOf(fieldMap.get(fieldName).getDescribe().getLength());
//add the rec to a list for insert
myDefs.add(myDef);
}
//do the insert
insert myDefs;
**********************
3. Create a report on your custom object
Now, you may mess up at some point or maybe your schema has been updated. No worries, just add a few lines to the anonymous apex to delete all of the rows in the reporting object that holds the invalid/outdated schema and re-run the script.
No comments:
Post a Comment