Thursday, October 27, 2016

Apex Describe Methods

In dynamic SOQL, it is very critical to check if Object exists and related field also exists. Nothing fancy, but below code comes quite handy to check if Object and field exists:

      public static boolean fieldExists(String objectName, String fieldName) {  
           try {  
                Schema.SObjectType salesforceObject = Schema.getGlobalDescribe().get(objectName);  
                Map<String, Schema.SObjectField> fields = salesforceObject.getDescribe().fields.getMap();  
                for(String field : fields.keySet() ) {  
                     if( field.equalsIgnoreCase(fieldName) ) {  
                          return true;  
                     }  
                }  
           } catch(Exception e) {  
                System.debug(e);  
                return false;  
           }  
           return false;  
      }  
      public static boolean relationshipExists(String objectName, String relationshipName) {  
           try {  
                Schema.SObjectType salesforceObject = Schema.getGlobalDescribe().get(objectName);  
                Map<String, Schema.SObjectField> fields = salesforceObject.getDescribe().fields.getMap();  
                for(String field : fields.keySet() ) {  
                     if( fields.get(field).getDescribe().getType() == Schema.DisplayType.Reference && fields.get(field).getDescribe().getRelationshipName() != null && fields.get(field).getDescribe().getRelationshipName().equalsIgnoreCase(relationshipName) ) {  
                          return true;  
                     }  
                }  
           } catch(Exception e) {  
                System.debug(e);  
                return false;  
           }  
           return false;  
      }  


To Verify:

 Boolean b1 = relationshipExists('Account','Owner');  
 Boolean b2 = relationshipExists('Quote','Owner');  
 Boolean b3 = relationshipExists('ACCOUNT','OWNER');  
 Boolean b4 = relationshipExists('ACCOUNT','OWNER-');  
 System.debug(' b1 ' + b1 );  
 System.debug(' b2 ' + b2 );  
 System.debug(' b3 ' + b3 );  
 System.debug(' b4 ' + b4 );  

Results:

 b1 true  
 b2 false  
 b3 true  
 b4 false  

No comments: