function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Swamy PSwamy P 

convert string to sobjectfield API name

Hello Everyone,

I was trying to Convert String to a SobjectField API Name but unfortunately not able to convert it, here is my code. 
     Map <String, Schema.SObjectField> fieldMap = Schema.getGlobalDescribe().get('O_Product__c').getDescribe().fields.getMap();
              Map<String,String> POIMap= new Map<String,String>();  -->Here In this map I'm capturing Field Label and Name
             for(Schema.SObjectField sfield : fieldMap.Values())
             {
              schema.describefieldresult dfield = sfield.getDescribe();         
              POIMap.put(dfield.getLabel(),dfield.getname());
             }

String fldApi = POIMap.get('Value for '+newLead.CurrencyIsoCode); --> Here I want to convert "fldApi" into SobjectField API Name
How can we Convert it String into Field API Name?
Girija Joshi 14Girija Joshi 14
what do you mean by convert string to API name?  You want to get the API name and store that name intp String?
Girija Joshi 14Girija Joshi 14
Swamy,

public class FieldMap{
    public static void GetFielsName() {
        list<String> fieldStr = new List<String>();
        Map<String, Schema.SObjectField> schemaFieldMap = Account.sObjectType.getDescribe().fields.getMap();
        for (String field : schemaFieldMap.keySet()) {            
            fieldStr.add(field);
        }
        
        integer cnt = 0;
        for(String f:fieldStr) {
            System.debug('---- Field[' + cnt + '] :' + f);
            cnt = cnt + 1;
        }
        
    }
}

If what are asking as above.
Ajay K DubediAjay K Dubedi
Hi Swamy,
You can try like this:

String testString = 'Account.example__c';

List<String> splitString = testString.split('\\.');

Schema.SobjectField theField = Schema.getGlobalDescribe().get(splitString[0]).getDescribe().fields.getMap().get(splitString[1]);
This obviously has no error handling in it, but hopefully it gets you started.

Or breaking this down to understand it:

String testString = 'Account.example__c';

List<String> splitString = testString.split('\\.');

// store the object/field names
String objectName = splitString[0];
String fieldName = splitString[1];

// get the SObjectType

Schema.SObjectType objectType = Schema.getGlobalDescribe().get(objectName);

// get the fields on the object

Map<String, SObjectField> fieldMap = objectType.getDescribe().fields.getMap();

// The key to the map is the API name of the field

Schema.SobjectField theField = fieldMap.get(fieldName);

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi