Skip to content

Instantly share code, notes, and snippets.

@hasanthaera
Created April 23, 2015 06:36
Show Gist options
  • Save hasanthaera/005de4e4588aa8f8260f to your computer and use it in GitHub Desktop.
Save hasanthaera/005de4e4588aa8f8260f to your computer and use it in GitHub Desktop.
Generic way to update Record Type with a trigger based on a passed value
/**
* getRecordTypeId
* Author: Hasantha Liyanage
* Created: 2014-12-01
* Arguments: sobjectName: the name of the object we want to get the record type for;
* recordTypeName: the name of the record type we want to fetch
* Returns: If found returns the id of the record type, if not returns null. This
* method retrives recordtypes with using metadata.
**/
public static Id getRecordTypeId(String sobjectName, String recordTypeName) {
Map<String, Schema.SObjectType> sObjectMap = Schema.getGlobalDescribe();
// getting Sobject Type
Schema.SObjectType s = sObjectMap.get(sobjectName);
Schema.DescribeSObjectResult resSchema = s.getDescribe();
//getting all Recordtype for the Sobject
Map<String,Schema.RecordTypeInfo> recordTypeInfo = resSchema.getRecordTypeInfosByName();
//particular RecordId by Name
return recordTypeInfo.get(recordTypeName).getRecordTypeId();
}
/**
* setCustomRecordType
* Author: Hasantha Liyanage
* Created: 2014-12-01
* Arguments: Object type name, dummy picklist field name, List of objects which the trigger returns as Trigger.new
* Returns: void/ updates the recordtypes
**/
public static void setCustomRecordType(String typeName, String fieldName, List<sObject> objectsList) {
// iterate through object list
for (sObject obj: objectsList) {
String selectedValue = String.valueOf(obj.get(fieldName));
// update the recordtype with picklist selected value
Id oid = getRecordTypeId(typeName,selectedValue);
obj.put('RecordTypeId',oid);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment