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– EricSep 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 CSep 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.– cropredyNov 12, 2020 at 18:36
2 Answers
An alternate way to do this without going through Schema.getGlobalDescribe():
String myString = 'Account';
SObjectType sObjType = ((SObject) Type.forName(myString).newInstance())
.getSObjectType();
-
I was going to ask what the difference is, then I found this QandA: salesforce.stackexchange.com/questions/218982/…– Nick CFeb 13, 2019 at 0:24
-
@NickCook - cool; I remember sfdcfox's answer and have cross-linked to it– cropredyFeb 13, 2019 at 1:19
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();