Tuesday, 13 February 2018

Salesforce - How to get the API names of all objects that are related to an object.


Below code returns the all the related objects API names for the object Custom_Object__c.

Set<String> results = new set<String>();
for( ChildRelationship r: Custom_Object__c.SObjectType.getDescribe().getChildRelationships())
    results.add(string.valueOf(r.getChildSObject()));
System.debug(string.join(new List<String>(results),',');



for instance, to get all the related objects of Account, just replace Custom_Object__c in the above code like this,

Set<String> results = new set<String>();
for( ChildRelationship r: Account.SObjectType.getDescribe().getChildRelationships())
    results.add(string.valueOf(r.getChildSObject()));
System.debug(string.join(new List<String>(results),',');


The output is the comma separated list of all the related objects.


Get All apex classes related to an object:

1) create a contact record and use this contactId as parentId for the attachment.
2) replace the objectName with the list of objects separated by comma.
3) run the below code in dev console and download the file as csv.

String objectName='Task,AttachedContentDocument,Attachment,CombinedAttachment,ContentDocumentLink,ContentVersion,EmailMessage,EmailStatus,EntitySubscription,FeedComment,FeedItem,FlowRecordRelation,NetworkActivityAudit,PartnerNetworkRecordConnection,Task,TaskFeed,TopicAssignment';

List<String> objlist=objectName.split(',');
List<ApexClass> classeslist=[SELECT Id, Name,lastmodifiedby.name, Body FROM ApexClass order by Name];
String records='';
integer counter=0;
for(String ky:objlist){
for(ApexClass c:classeslist){
if(c.Body.containsIgnoreCase(ky) || c.Name.containsIgnoreCase(ky)){
records+=c.Name+',ApexClass,'+c.lastmodifiedBy.name+',ApexClass.'+c.Name+','+ky+'\n';
counter++;
}
}
}

//create attachment
Attachment att=new Attachment();
att.name='Complaints.csv';
att.parentId='0035B00000IStwD';
att.contenttype='csv';
att.body=Blob.valueOf(records);
insert att;
System.debug('file created with total records: '+counter);



No comments:

Post a Comment