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
Gene T.Gene T. 

Activate Trigger on specific record type

Hi,

 

I have a trigger on the Contact object that creates a new record on a custom object called Student.

 

 

trigger CreateStudentFromContact on Contact (after insert) {
  
    List<Student__c> Students = new List<Student__c>();
    for(contact c:trigger.new)
    {
     student__c s=new student__c(
         name=''+c.firstName +' ' +c.lastName, 
         contact__c=c.id, 
         Birthdate__c=c.Birthdate,
         Description__c=c.Description,
         Email__c=c.Email,
         Family__c=c.AccountID,
         Gender__c=c.Gender__c,
         Home_Phone__c=c.HomePhone,
         Lead_Source__c=c.LeadSource,
         Mailing_City__c=c.MailingCity,
         Mailing_Country__c=c.MailingCountry,
         Mailing_State_Province__c=c.MailingState,
         Mailing_Street__c=c.MailingStreet,
         Mailing_Zip_Postal_Code__c=c.MailingPostalCode,
         Mobile__c=c.MobilePhone,
         Phone__c=c.Phone,
         Program_of_Interest__c=c.Program_of_Interest__c,
         Promotion__c=c.Promotion__c    
     );
        
        
        Students.add(s);
    }
    
    if (!Students.isEmpty()) {
      insert Students;
    }

 I would like to make it so that the trigger only activates if the contact Record Type is equal to "Student". Any Advice on how to do this?

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox
trigger ... {
map<id, recordtype> recordTypes = new map<id, recordtype>(
[select id,name from recordtype where sobjecttype='contact']);
student__c[] students = new student__c[0];
for(contact c:trigger.new) {
  if(recordTypes.get(c.recordtypeid)!=null&&recordtypes.get(c.recordtypeid).name=='Student') {
  students.add(new student__c(...));
}
}
if(!students.isempty()) {
  insert students;
}
}

 

All Answers

sfdcfoxsfdcfox
trigger ... {
map<id, recordtype> recordTypes = new map<id, recordtype>(
[select id,name from recordtype where sobjecttype='contact']);
student__c[] students = new student__c[0];
for(contact c:trigger.new) {
  if(recordTypes.get(c.recordtypeid)!=null&&recordtypes.get(c.recordtypeid).name=='Student') {
  students.add(new student__c(...));
}
}
if(!students.isempty()) {
  insert students;
}
}

 

This was selected as the best answer
Gene T.Gene T.

Thanks for the reply on a Sunday night. I amended the code with yours but I get this error, Any Ideas?

 

sfdcfoxsfdcfox

Sorry. I was typing too fast. On the line in question, it should be "c.RecordTypeId" instead of "c.RecordType" (in both cases). I'll amend my previous post with that change.