Simple-to-use “if field exists” logic?

Is there simple to use logic that equals “if a field exists, then…“:

if( **fieldname__c exists** ) then { ... }

..? I really don’t want to have to worry about a ton of class or other logic. I’m hopeful someone has a clue what to replace the if clause with, because I have no idea.

This is to come up with a much more simplistic fix for a problem I’ve been trying to resolve via two other questions. :-/

1: After Delete – Need To “Cleanup” When An Opp Is Deleted

2: Apex TRY … CATCH … FINALLY Syntax

Having this would give me the solution I need (but more specifically that I want without having a ton of code or yet another Trigger).

Added Note: My fallback IS GOING to be the TRY-CATCH logic. I’m just hopeful there is something more elegant / appropriate.


Use the Describe methods. In the example below, replace My_Object__c with the name of the pertinent sObject.

Set<String> objectFields = Schema.SObjectType.My_Object__c.fields.getMap().keySet();
if(objectFields.contains(fieldName)) {
  //do stuff

Note, don’t repeatedly call Schema.SObjectType.My_Object__c.fields.getMap() as there are governor limits around describe calls. Call it once and save the list.

Source : Link , Question Author : AMM , Answer Author : Phil Rymek

Leave a Comment