“Future-Resistant” Custom Clone


There have been quite a few times that through the process of coding a Force.com solution that “can you clone that?” comes up.  “Easy enough!” one says, until 6 months down the road you get the call that “it’s not working!” and you come to find out they added a new field that wasn’t in your SOQL query and it’s not pulling over.

Fun.

So, here’s some code that you can use to make your clone (or insert other use-case) future “resistant”.  =)

// Id from earlier in your class
Id idCase = some value;

// Gather List of all Createable Case Fields
String strFields = ”;
SObjectType sot = Schema.getGlobalDescribe().get(‘Case’);
List<Schema.SObjectField> lstFields = sot.getDescribe().fields.getMap().values();
for(Schema.Sobjectfield so : lstFields) {
Schema.DescribeFieldResult dfr = so.getDescribe();
if (dfr.isCreateable()) {
strFields += dfr.getName() + ‘,’;
}
}

// Create Source Case Object
if (strFields.endsWith(‘,’)){strFields = strFields.substring(0,strFields.lastIndexOf(‘,’));}
String strQuery = ‘SELECT ‘ + strFields + ‘ FROM Case WHERE Id = :idCase’;
Case cSource = Database.query(strQuery);

// Clone and Insert Clone
Case cTarget = cSource.clone();
cTarget.Subject = cTarget.Subject + ‘ – Clone’;
insert cTarget;

I’m not the biggest proponent for Dynamic SOQL, but this use-case seems pretty safe.  If you have recommendations on how I could improve this for speed / safety, please let me know in the comments!

Thanks for reading!

Advertisements

One thought on ““Future-Resistant” Custom Clone

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s