Thursday, 2 March 2017

Creating Sobject or List of Sobject Dynamically in Apex Saelsforce

public class Utility {
    public static SObject createDynamicObject(String objectApiName) {        
        return (SObject)Type.forName(objectApiName).newInstance();
    }
    public static List createDynamicList4object(String objectApiName) {
        return (List)Type.forName('List<'+objectApiName+'>').newInstance();
    }
    /*** Usage ***
    List recs = Utility.createDynamicList4object('Contact');
    SObject rec1 = Utility.createDynamicObject('Contact');
    rec1.put('LastName','March2017-3');
    SObject rec2 = Utility.createDynamicObject('Contact');
    rec2.put('LastName','March2017-4');
    recs.add(rec1);
    recs.add(rec2);
    insert recs;
    */
}

No comments:

Post a Comment