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
ABC XYZ 39ABC XYZ 39 

Use RecordType Name in Triggers.?

Hi, I need to return only specific records by recordtype name. How do I implement this in trigger . Thanks
Best Answer chosen by ABC XYZ 39
Amit Chaudhary 8Amit Chaudhary 8

Some time in code we need to get recordTypeId . For that generally we used SOQL like below :-
 
Id contRecordTypeId = [Select id from RecordType where sObjectType = 'Contact' and developerName ='NameOfRecordType' ].id ;

You can try below Describe to get record Type Id without SOQL
 
Id contRecordTypeId = Schema.SObjectType.Contact.getRecordTypeInfosByName().get('NameOfRecordType').getRecordTypeId();


Sample Trigger code for you.
Trigger AccountTrigger on Account (before insert) 
{
	Id AccRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('NameOfRecordType').getRecordTypeId();
	For(Account acc : Trigger.new)
	{
		if(acc.RecordTypeId == AccRecordTypeId)
		{
			// Do your work here
		}
	}	
}

PLease let us know if this will help you
 

All Answers

JethaJetha
First you need to make a SOQL on RecordType Object to find RecordTypeID. As Below :

RecordType rt = [SELECT Id, Name FROM RecordType WHERE Name = 'Your Record Type Name'];

In your trigger you can filter on your records by simply Where RecordTypeId = rt.Id;

Please let me know if you face any issue..............
Pankaj_GanwaniPankaj_Ganwani
Hi ABC,

You can achieve this using below mentioned 2 approaches:

1. Fetch the record type Id using SOQL:

RecordType rt = [SELECT Id FROM RecordType WHERE DeveloperName = 'RecordTypeAPIName'];

2. Using desribe call:

Id devRecordTypeId = Schema.getGlobalDescribe().get('Account').getDescribe().getRecordTypeInfosByName().get('recordtypenamelabel').getRecordTypeId();

Using 2nd approach your one SOQL usage will be prevented.
Amit Chaudhary 8Amit Chaudhary 8

Some time in code we need to get recordTypeId . For that generally we used SOQL like below :-
 
Id contRecordTypeId = [Select id from RecordType where sObjectType = 'Contact' and developerName ='NameOfRecordType' ].id ;

You can try below Describe to get record Type Id without SOQL
 
Id contRecordTypeId = Schema.SObjectType.Contact.getRecordTypeInfosByName().get('NameOfRecordType').getRecordTypeId();


Sample Trigger code for you.
Trigger AccountTrigger on Account (before insert) 
{
	Id AccRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('NameOfRecordType').getRecordTypeId();
	For(Account acc : Trigger.new)
	{
		if(acc.RecordTypeId == AccRecordTypeId)
		{
			// Do your work here
		}
	}	
}

PLease let us know if this will help you
 
This was selected as the best answer
ABC XYZ 39ABC XYZ 39
Thank you all...