15

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.

  • 2
    E.J. Wilburn covered this amazingly well in an answer to a similar question: salesforce.stackexchange.com/a/1056/60 In short, describes are conceptually cleaner but notably worse in real-world situations. Try/catch with dynamic apex is "ugly" but efficient. – ca_peterson Apr 17 '13 at 22:06
24

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.

  • Thanks for the insight (and to @ca_peterson for the link as well). When I get back to working on this, I am going to implement what I've learned here, and already have ideas on keeping the code relatively small based on how the fields are named. Thanks again! – AMM Apr 18 '13 at 15:37
  • 3
    Limits for all Apex describe calls have been removed in Summer '14 – Vadim Rudkov Aug 17 '16 at 16:06
  • 1
    Please note here that objectFields will contain all fields in lowercase. So in contains() method, you need to do fieldName.toLowerCase() – Sarang Nov 1 '18 at 9:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.