9

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.

  • 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 '14 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 '14 at 8:45
20

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();
7

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

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

speed comparison between above and getXXDescribe methods

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.