function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ss kumarss kumar 

create trigger cls on object to differentiate the two record types

my requirment is i've one object in this object i've two record types .when ever i create or update the record i want to display the specific record type name in decription field.
Arun Kumar 1141Arun Kumar 1141
Hello,

If you want that your record description fiels to contain Record Type name then you can try this trigger.

Trigger :-
trigger RecordTypetrigger on Account (before insert) {
 if (Trigger.isBefore) {
        if (Trigger.isInsert || Trigger.isUpdate) {
            RecordTypeHandler.updateRecordTypeDescription(Trigger.new);
        }
    }
}
Handler Class :-
public class RecordTypeHandler {
public static void updateRecordTypeDescription(List<Account> records) {
        // Retrieve the record type name for each record
        Map<Id, Schema.RecordTypeInfo> recordTypeMap = Account.SObjectType.getDescribe().getRecordTypeInfosById();
        
        for (Account record : records) {
            if (recordTypeMap.containsKey(record.RecordTypeId)) {
                String recordTypeName = recordTypeMap.get(record.RecordTypeId).getName();
                record.Description = recordTypeName;
            }
        }
    }
}


Here you can replace "Account" with your object name and "Description" with your own custom field name.

I hope it will help you!

Thanks.
 
SubratSubrat (Salesforce Developers) 
Hello ,

For your requirement, you can create a trigger on the object and update the description field with the name of the specific record type whenever a record is created or updated. Here's an example of how you can implement it:
trigger UpdateDescriptionOnRecordType on MyObject__c (before insert, before update) {
    public static void updateDescription(List<MyObject__c> objects) {
        Map<Id, Schema.RecordTypeInfo> recordTypeMap = MyObject__c.SObjectType.getDescribe().getRecordTypeInfosById();
        
        for (MyObject__c obj : objects) {
            Schema.RecordTypeInfo recordType = recordTypeMap.get(obj.RecordTypeId);
            if (recordType != null) {
                obj.Description__c = recordType.getName();
            }
        }
    }
    
    if (Trigger.isBefore) {
        if (Trigger.isInsert) {
            updateDescription(Trigger.new);
        } else if (Trigger.isUpdate) {
            updateDescription(Trigger.new);
        }
    }
}
This trigger will fire before the records are inserted or updated. It retrieves the record type information using the getRecordTypeInfosById() method on the object's Describe result. It then updates the Description__c field with the name of the record type for each record in the trigger context.

If this helps , please mark this as Best Answer.
Thank you..