Friday 15 July 2016

Code to Get All Parent and Child Object For A Give Object


Parent Object


Set<String> testName= new set<String>();

public Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();

Map <String, Schema.SObjectField> fieldMap = schemaMap.get('Account').getDescribe().fields.getMap();
for(Schema.SObjectField sfield : fieldMap.Values())
{
schema.describefieldresult dfield = sfield.getDescribe();


if(dfield.getRelationshipName()!=null){
SObjectField sObjfieldName  =dfield.getSobjectField();
//System.debug(sObjfieldName  );
String abc=sObjfieldName  +'';

Map<String, Schema.SobjectField> fields = Account.getSObjectType().getDescribe().fields.getMap();

Schema.DescribeFieldResult f=fields.get(abc).getDescribe();



for(Schema.SObjectType reference : f.getReferenceTo()) {
testName.add(reference.getDescribe().getName());
}

}


}

for(String itr :testName){
System.debug(itr );
}


Child Object

// To Retrieve Sechma of the given Object
Schema.DescribeSObjectResult R = Account.SObjectType.getDescribe();
// Reterieving relation ship field
List<Schema.ChildRelationship> C = R.getChildRelationships();
Set<String> abc= new Set<String>();
// iterating all the fields
for (Schema.ChildRelationship child : r.getChildRelationShips()) {
   // from field getting its sobject describe call
   Schema.DescribeSObjectResult childDesc = child.getChildSObject().getDescribe();
   // from that getting its name and passing in set
   abc.add(childDesc.getName());
}
for(String itr :abc){
System.debug(itr);
}