Thursday, May 2, 2013

Apex Class to get record type Id and name using developer name


public with sharing class Util {

    private static map<String, Id> mapRecordTypes = new map<String, Id>();   


    public static Id getRecordTypeId(String rtObject, String rtName) {
     try {
      String rtKey = rtObject + '-' + rtName;

      if (!mapRecordTypes.containsKey(rtKey)) {
       System.debug('\n ### Queries: ' + Limits.getQueries() + '/' + Limits.getLimitQueries());
       Id rid = [Select r.Id From RecordType r where r.SobjectType = : rtObject and (r.Name = : rtName OR r.DeveloperName = : rtName) and r.IsActive = true].Id;
       system.debug('\n ### Adding RecordType Id ' + rid +  ' for Sobject ' + rtObject + ' RecordType ' + rtName);
    mapRecordTypes.put(rtKey, rid);
      }
      return mapRecordTypes.get(rtKey);

     } catch (Exception ex) {
      return null;
     }
    }
}



Regards,
Sagar Kavati,
Salesforce developer,
Cloud Credence.

Apex Code for Lead Conversion depending upon Status and Recordtype


trigger leadconvert on Lead (After Insert, After Update) {
try{

LeadStatus convertStatus;
List<Database.LeadConvert> leadConversions = new List<Database.LeadConvert>();

for(Lead ld:trigger.new){

 if(ld.Status == 'Active' && ld.RecordTypeId == Util.getRecordTypeId('Lead', 'Company')){

     if (convertStatus == null) convertStatus = [SELECT  MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];

   Database.LeadConvert lc = new database.LeadConvert();
   lc.setLeadId(ld.id);
   lc.setConvertedStatus( convertStatus.MasterLabel);
   lc.setDoNotCreateOpportunity(true);
    leadConversions.add( lc );

  }

 if (!leadConversions.isEmpty()) Database.convertLead(leadConversions);

}

} catch(Exception ex){
 throw ex;
}
}


/////////////////////////////////  Util Class code /////////////////////////////////  

public with sharing class Util {

    private static map<String, Id> mapRecordTypes = new map<String, Id>();   


    public static Id getRecordTypeId(String rtObject, String rtName) {
     try {
      String rtKey = rtObject + '-' + rtName;

      if (!mapRecordTypes.containsKey(rtKey)) {
       System.debug('\n ### Queries: ' + Limits.getQueries() + '/' + Limits.getLimitQueries());
       Id rid = [Select r.Id From RecordType r where r.SobjectType = : rtObject and (r.Name = : rtName OR r.DeveloperName = : rtName) and r.IsActive = true].Id;
       system.debug('\n ### Adding RecordType Id ' + rid +  ' for Sobject ' + rtObject + ' RecordType ' + rtName);
    mapRecordTypes.put(rtKey, rid);
      }
      return mapRecordTypes.get(rtKey);

     } catch (Exception ex) {
      return null;
     }
    }
}





Regards,
Sagar Kavati,
Salesforce developer,
Cloud Credence.