4

I have a custom setting where I have fields api name and getting the field api name and use with sObject. At that time I am getting error cannot use string with the sObject. How can I convert the string to a sObjectField or is there any other way to do it. my code

 Map<String, SObjectField> fieldMap = SObjectType.CVSR__Visit__c.fields.getMap();

    for(String fieldName : map_customSet.keyset()){

        system.debug('field map ' + fieldMap.get(fieldName));
        SObjectField sObjfieldName = fieldMap.get(fieldName);

        //system.debug('Visit Field ' + v.sObjfieldName );


    }
6

You can access SObject fields using Strings (as well as using SObjectField tokens): see the get and put methods listed in the sObject Class documentation.

So generally there is not much benefit in first converting the String to the corresponding SObjectField token. But if you want to do that it is possible via this map for any SObject:

Map<String, SObjectField> m = SObjectType.Account.fields.getMap();

PS

The way that you access fields using strings (or SObjectField tokens) is via get and put:

CVSR__Visit__c v = ...;
String sObjfieldName = 'Name';
String v = (String) a.get(sObjfieldName);

Also note that if this code is running outside of the CVSR managed package and the field is part of the CVSR managed package, you will need to include the "CVSR__" prefix on the field name in your custom setting.

  • when i try to access field from my object v.sObjfieldName it is getting error that Error: Compile Error: Invalid field sObjfieldName for SObject CVSR__Visit__c at line 30 column 43 – Anu Sep 3 '14 at 9:01
  • @Anu See the PS. – Keith C Sep 3 '14 at 9:15
  • i still do have the same issue Error: Compile Error: Incompatible types since an instance of Schema.SObjectField is never an instance of String a – Anu Sep 3 '14 at 9:23
  • @Anu That error message is different and gives you a hint about how to fix the problem. – Keith C Sep 3 '14 at 9:39

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.