16

I have a object A where I am saving the name of the object as Strings and the fields also as String. Eg: If I have object Account, contact and opp objects. I am saving object Account as object Name field in A obj as string and field Name to another field as string. same as with contact and opp. Here when I loop through the records from the A object I need to display the Account on to my VF page. The datatype of the field should be same so that it can display as it is. Is anyone over here can help me out for this issue.

3
  • Can you provied any code you have so far? Your explanation is difficult to follow. Seems to me all you need is a Map<String,Map<String,String>> Object Name as String => Field Name As String => Field Value as String
    – Eric
    Sep 27, 2014 at 7:10
  • You can write Apex/Visualforce where the SObject types are explicit and the compilers help check your code. Or you can use the "dynamic" approach where queries are represented as Strings and SObjects and SObject fields are accessed through maps using String keys (or SObjectType and SObjectField token keys) in both Apex and Visualforce. But the latter does not require that "datatype of the field should be same so that it can display as it is". Can you add more information about what you are trying to accomplish overall?
    – Keith C
    Sep 27, 2014 at 8:45
  • Anu - you've got two solid answers here with lots of upvotes - suggest you choose one as a service to the Community.
    – cropredy
    Nov 12, 2020 at 18:36

2 Answers 2

29

An alternate way to do this without going through Schema.getGlobalDescribe():

String myString = 'Account';
SObjectType sObjType = ((SObject) Type.forName(myString).newInstance())
                                  .getSObjectType();

speed comparison between above and getXXDescribe methods

2
25

Here is the way:

// I have Account name in String
String objectStr = 'Account';

// Convert to schema.sObjectType
Schema.SObjectType convertType = Schema.getGlobalDescribe().get(objectStr);

// Create an instance of that type
Sobject genericObject = convertType.newSObject();

// or if I know it is Account !! why making Sobject ?
Account acc = (Account)convertType.newSObject();
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .