Pages

Thursday, October 6, 2011

Reduce Deployment Pains (pt. 1): Record Types

Let's get this ball rolling right away. One amateur mistake that continually haunts my early code is the hard coding of RecordTypeIDs. Remember, I'm new to the development game and have preached and have been preached at to not hard code anything.

Yeah, well under a tight deadline I was more than happy to throw that to the wind. Now everytime I go to deploy some old code from a sandbox, I'll get nagged with some sort of error message that the RecordTypeID doesn't exist in production.

Ah rats, busted. I created the record type outside of the sandbox or after the sandbox was created and now my record type IDs don't match up. What I would do before is just update the ID, deploy, and be on my merry way.

Wrong.

The better way to specify things like IDs will always be to query them so you have the latest and greatest, despite your environment.

Check out this little ditty:

public list<recordType> RecordTypes= new list<recordType>();
public map<string,id> RecordTypes_Map = new map<string,id>();

public YourClass(ApexPages.StandardController controller) {
    RecordTypes = [select id, name from recordtype where sObjectType = 'YourObjectAPI__c'];
    if(RecordTypes.size()>0){
        for(recordtype r:RecordTypes){
            RecordTypes_Map.put(r.name,r.id);
        }
    }
}

I'm creating a map of all the names and IDs of recordtypes for a particular object (don't forget to chance 'YourObjectAPI__c').

Then within the section of code I want to retrieve the ID, I just use:
NB_RecordTypes_Map.get('Name of Your Record Type'));

The obvious caveat here is if your record type name doesn't exist or has changed between your production and sandbox instances. Salesforce will probably puke all over itself in that event, so it probably wouldn't hurt to include some safe guard catches in your code.