Monday, 23 July 2018

Get RecordType Name inside Trigger

When you are going through loop in a trigger you don’t have access to Record Type name like RecordType.Name, you can only access Id as RecordTypeId
1trigger TriggerName on Account (after insert, after update) {
2    for (Account o : Trigger.new) {
3    type = o.RecordTypeId;
4}
RecordTypeId works, because that’s the actual field on Account (a lookup to RecordType). And as with all lookup fields in a trigger, to get the related value, you need to query for it.
However, you can also use before your loop
1Map<ID, Schema.RecordTypeInfo> rtMap = Schema.SObjectType.Account.getRecordTypeInfosById();
and then inside your loop:
1type = rtMap.get(o.RecordTypeId).getName();

No comments:

Post a Comment