0

Unable to get recordType name by this.triggerNew[0].recordType.Name.It is return null.

 public CustomerInfoHandler() {
        this.triggerNew = (List<CustomerInfo__c>) Trigger.new;
    }

    public override void beforeInsert() {
        String customerID = this.triggerNew[0].recordType.Name + getToday() + '-' + getAutoNumber(this.triggerNew[0].recordType.Name);
        this.triggerNew[0].customerID__c = customerID;
    }

2 Answers 2

1

You can't access parent objects without obtaining them somehow. Since we're talking about record types, you can:

// Static variable inside class, outside method
static Map<Id, RecordTypeInfo> recordTypes = sObjectType.CustomerInfo__c.getRecordTypeInfosById();
public override void beforeInsert() {
  String recordTypeName = recordTypes.get(this.triggerNew[0].RecordTypeId)?.getName();
  String customerID = recordTypeName + getToday() + '-' + getAutoNumber(recordTypeName);
  this.triggerNew[0].customerID__c = customerID;
}

Note that you should make sure this method is bulkified.

0

You cannot get RecordTypeName or RecordTypeDeveloperName directly from trigger.

Instead try creating a util class.

    public String getRecordTypeDeveloperNameFromId(Schema.SObjectType sObjType, Id recordTypeId, String sObjectAsString) {
        initialize(sObjType, sObjectAsString);
        if (mapRecordTypeById.get(sObjectAsString).containsKey(recordTypeId)) {
            Schema.RecordTypeInfo recordTypeInfo = mapRecordTypeById.get(sObjectAsString).get(recordTypeId);
            return recordTypeInfo.getDeveloperName();
        }
        return null;
    }

    private void initialize(Schema.SObjectType sObjType, String sObjectAsString) {
        if (!mapRecordTypeByName.containsKey(sObjectAsString) || !mapRecordTypeById.containsKey(sObjectAsString)) {
            Schema.DescribeSObjectResult describeObjectResult = sObjType.getDescribe();
            mapRecordTypeByName.put(sObjectAsString, describeObjectResult.getRecordTypeInfosByName());
            mapRecordTypeById.put(sObjectAsString, describeObjectResult.getRecordTypeInfosById());
            mapRecordTypeByDeveloperName.put(sObjectAsString, describeObjectResult.getRecordTypeInfosByDeveloperName());
        }
    }

And then use it like below.

System.debug(YOURCLASS.getRecordTypeDeveloperNameFromId(Case.getSObjectType(), 'RecordTypeIdFromTrigger', 'Case'));

You can pass the Id of the record type and it will fetch you the record type developername.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .