The Silver Lining

Lessons & Learnings from a salesforce certified technical architect.

Posts Tagged ‘SObject

Salesforce: Instantiating an SObject Dynamically at Run-time

with 13 comments

I’m sure a lot of you have this documented somewhere but I’ve recently discovered that it’s quite difficult to find an obvious reference to this knowledge on the interwobbles. So how would you create a Generic SObject at run-time? It’s rather easy thankfully:

String sObjectName = 'MyObject__c';
Schema.SObjectType t = Schema.getGlobalDescribe().get(sObjectName);
SObject s = t.newSObject();

If you require this type of functionality quite often I’d suggest putting it in a utility class.


Written by Wes

January 25, 2011 at 8:54 pm

Lists of SObjects and Classes – By value or reference?

with 3 comments

I found a quirky bug in my code some time back, and realised that the cause of the bug was quite a useful Apex feature viz. SObjects and Apex classes are passed by reference and not value.

What does this mean you say? Let’s start by defining what passing by value means.

In a nutshell, if you pass a variable to a method and it’s a primitive type(Integer, String etc.) it will be passed by value meaning that the value of the variable and not the variable itself is passed to the method Read the rest of this entry »

Written by Wes

August 3, 2009 at 12:48 pm

Instantiating an empty list of SObjects

leave a comment »

You’re building a dynamic Apex class so general you’re thinking about promoting it to colonel. You’ve slogged through the Salesforce documentation on the topic, a feat in itself, but are having issues instantiating an empty list of SObjects to be processed in some way.

If you attempt to do this in the seemingly Salesforce manner i.e.

List<SObject> sobjects = new List<SObject>();

You will receive the following error: Compile error: Only concrete SObject lists can be created

This can be rather frustrating as this type of data structure is one of the more commonly used. There are however 3 workarounds, one slightly more elegant than the rest.

NB myObject is a SObject.

List<SObject> sobjects = Database.query('select id from ' + myObject.getSObjectType() +' where id=null');
String searchquery='FIND\'xxx\'IN ALL FIELDS RETURNING '+ myObject.getSObjectType() +'(name)';
List<List<SObject> searchList=search.query(searchquery);
List<SObject> sobjects = searchlist[0];

or finally you could use a wrapper class (I’m a huge fan of wrapper classes on this platform)

List sobjects = new List();

public class myObject{

sObject obj {get; set;}

public myObject(sObject obj){
this.obj = obj;

Gratefully this is not a problem you will encouter often, but it is a complex area that can be further complicated by workarounds. But what doesn’t kill you (usually) makes you stronger.

Written by Wes

June 8, 2009 at 12:13 pm

%d bloggers like this: