+ Start a Discussion
linshelllinshell 

Apex Trigger Question

I had someone help me with an Apex Trigger on the Lead object that takes the Case ID number from a text field  and populates the lookup field to create a link to the actual case.  Problem is I only want the trigger to work for a specific Lead record type.  I believe I would have to add the following but am not sure where it would go in the current statement: 

if (RecordTypeId=’012600000005EJy’)

 

This is the current Apex Trigger code:

 

trigger PopulateCaseId on Lead (before insert) {
String caseId = Trigger.new[0].Case_Number__c;
Trigger.new[0].Case__c = [SELECT Id FROM Case WHERE Id = :caseId].Id;
}

 

 

bob_buzzardbob_buzzard

There are a couple of ways to get record type ids from apex:

 

 

           Id myRTId=Schema.SObjectType.MyObject__c.getRecordTypeInfosByName().get('Special').getRecordTypeId();

 or:

 

 

 

        id myRTID= [SELECT Id
                            FROM RecordType r 
                           WHERE r.Name  = 'Special' and r.SobjectType = 'MyObject__c'][0].ID;

 It's better to look them up based on name than rely on id, as ids can be different in sandboxes.

 

 

You can then take appropriate action based on the record type of the trigger element:

 

 

if (trigger.new[0].recordTypeId==myRTId)
{
   // do the special stuff here!
}

 I'm also duty bound to point out that your trigger is assuming only one item will be affected, which means that it wouldn't scale for bulk inserts.

 

 

 

 

 

 

linshelllinshell

Thanks for the feedback.  For this record type, bulk inserts would never be done.