0

I have a unique situation. I have several different SObjects that are using the same field API names and I'm trying to get them dynamically by passing the SObjectType. For instance. This is for a managed packages. I'm trying to avoid passing in the field name as string. Is there any other of way of doing this without using the field map?

public class RecordField {

    public static final String PKG_PREFIX = Utils.getPackagePrefix();
    public final Schema.SObjectField FIELD_ONE;
    public final Schema.SObjectField FIELD_TWO;

    public RecordField(Schema.SObjectType soType) {
         Schema.DescribeSObjectResult dsor = soType.getDescribe();
         Map<String, Schema.SObjectField> fieldMap = dsor.Fields.getMap();
         FIELD_ONE = fieldMap.get(PKG_PREFIX + 'Field_One__c');
         FIELD_TWO = fieldMap.get(PKG_PREFIX + 'Field_Two__c');
    }
}

Using the above class as an example (not exactly what I need to do, but for an example). I may not need to use a describe result for the field for all SObjects. I may only need the field in an SObject DML operation. I will probably ending up using an interface and implement it for each SObject.

public static void setRecords() {
     RecordField rf = new RecordField(Schema.Object_One__c.SObjectType) {
     // For instance I may need to get the label for one of the fields as they are not all the same
    String fldOneLbl = rf.FIELD_ONE.getDescribe().getLabel();
    // Or I may need to update the SObject with those field
    SObject s = [SELECT Id FROM Object_One__c LIMIT 1];
    if (rf.FIELD_TWO.getDescribe().isUpdateable())
        s.put(FIELD_TWO, 'Value');
    }

}
  • Are you trying to figure out all the field names two objects share in common? It's a little hard to grasp what you are trying to achieve. – Adrian Larson Jun 29 '17 at 14:02
  • @AdrianLarson Yes, I have multiple objects that share several fields with common names. Depending on the SObjectType I need to do different things with the DescribeFieldResult. So I want to to have an instance of the RecordField class for each SObjectType. – Andrew L. Jun 29 '17 at 15:11
  • Still very unclear. Please edit your post to clarify, and try to maybe include some input/output combos or some other way to make it more explicit what you wish to accomplish. – Adrian Larson Jun 29 '17 at 15:12
  • @AdrianLarson Sorry, I updated my question. Hope it's a bit more clear. – Andrew L. Jun 29 '17 at 15:35
  • you can create a new sObject and set Id and fields MyObj__c myObj = new MyObj__c(Id = YourQuriedId, FieldOne__c = YourValue1, FieldTwo__c = YourValue2); update myObj; – o-lexi Jun 30 '17 at 0:33

Your Answer

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

Browse other questions tagged or ask your own question.