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
Phuc 2Phuc 2 

Creating List object from string

Having an issue creating a List object from a string value.  The selectedObject value is coming over as a string value.  Trying to convert the string value so that it can be used as the object in  a list or a Map

Class
private Sobject selectedStringSobject;

selectedObject = 'CustomObject__c'
selectedStringSobject =Util.getSobjectFromString(selectedObject);

List<selectedStringSobject> newrecords = new List<selectedStringSobject>()

Util
public static SObject getSobjectFromString(String stringObject) {
        Map<String, Schema.SObjectType> obj = Schema.getGlobalDescribe(); 
        Schema.SObjectType so = obj.get(stringObject);
        
        Sobject newObject = so.newSobject();
        return newObject;
    }

error is : Invalid type: selectedStringSobject






 
Best Answer chosen by Phuc 2
Devid JohnDevid John

Try this way:

private Sobject selectedStringSobject;

String selectedObject = 'Account';
selectedStringSobject = getSobjectFromString(selectedObject);

List<Sobject> newrecords = new List<Sobject>();//This one should be change I guess

public static SObject getSobjectFromString(String stringObject) {
    Map<String, Schema.SObjectType> obj = Schema.getGlobalDescribe(); 
    Schema.SObjectType so = obj.get(stringObject);
    
    Sobject newObject = so.newSobject();
    return newObject;
}

All Answers

Devid JohnDevid John

Try this way:

private Sobject selectedStringSobject;

String selectedObject = 'Account';
selectedStringSobject = getSobjectFromString(selectedObject);

List<Sobject> newrecords = new List<Sobject>();//This one should be change I guess

public static SObject getSobjectFromString(String stringObject) {
    Map<String, Schema.SObjectType> obj = Schema.getGlobalDescribe(); 
    Schema.SObjectType so = obj.get(stringObject);
    
    Sobject newObject = so.newSobject();
    return newObject;
}
This was selected as the best answer
Phuc 2Phuc 2
Hey David thanks for the reply.  So where/when do I use the selectedStringSobject value?
Russell TysonRussell Tyson
Thanks for sharing the script of the string. As now I learned that I am doing mistake in the script of  our strawberries (https://breedium.com/can-bearded-dragons-eat-strawberries/) listing string. Which was resulting wrong data. When I updated the listing with the help of your share script so the results was fine and correct. Really appreciate you for the correct answer.