Oh my god. It's full of code!

Convert a string into a Salesforce Fieldname using regular Expressions

Hey all,

Another quick tip sample code type of post here (and probably not even ‘GOOD’ sample code, but at least functional). I had a requirment recently where I needed to create a dynamic query that will be built from some other values. Those values would represent fieldnames that needed to be queried but might not match exactly. So if the value the user selected was ‘My Big! FUN! Account (Acme LLC)’ that wouldn’t work in a query as field name because of all the special chars, spaces, etc. So I needed a bit of logic to clean up strings and attempt to convert them into valid Salesforce field names. I know this isn’t exactly the best approach, but this is within a limited set a values for an internal app, so it’s an understandable trade off. Anyway, enough excuses, let’s see some code.

//regular expressions to be used for replacing
string specialCharPatterns = '[^\\w]+';
string multiUnderscorePattern = '_+';

string fieldName = 'My Str!ng Th@t doesn't represent a valid F!eld   name(!)';

//replace special chars with underscores, and multiple underscores with one
fieldName = fieldName.replaceAll(specialCharPatterns,'_').replaceAll(multiUnderscorePattern,'_');

//remove leading underscores
fieldName = fieldName.left(1) == '_' ? fieldName.substring(1) : fieldName;

//remove trailing underscores
fieldName = fieldName.right(1) == '_' ? fieldName.substring(0,fieldName.length()-1) : fieldName;

//append custom field suffice
fieldName = fieldName + '__c';

string queryString = '';

queryString = 'select id, ' + fieldName + ' from Account';

list<sObject> sobjects = database.query(queryString);

    objectValue = (string) sobjects[0].get(fieldName);

So there ya go. A simple way to take a field, clean it up into a fieldname plug it into a query, and as a bonus extract the result. Have fun!

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s