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
UrvikUrvik 

Trigger to Create Contact Record

I am trying to create a contact record upon user record creation. It should only create a contact record if certain user role are selected. I have the following trigger which works fine if I remove IF statement for ROLE...could someone please help? Again, I have been trying to create a contact record upon creating user record only when certain ROLE are set for the user...Thanks..
trigger CreateContact on User (after insert) {    
    List<Contact> ur = new List<Contact>();
    for (User usr: Trigger.New){
	     if(usr.UserRole.Name=='role name'|| usr.UserRole.Name=='role name')      
              ur.add (new Contact(
                         FirstName = usr.FirstName,
                         LastName = usr.LastName));
                         
    }
	if(!ur.isEmpty())
        insert ur; 
}

 
magicforce9magicforce9
Hi,

Records in Trigger.New will not have access to UserRole.Name field as the field is further level down in relationship....You'll need to query for UserRole ids and then match that by looping the user records..see the code below.
trigger CreateContact on User (after insert) {    
    List<Contact> ur = new List<Contact>();
    Set<Id> rolesToBeChecked = (new Map<Id, UserRole>([Select Id from UserRole where Name = 'role name1' OR Name= 'role name2'])).keySet();
    for (User usr: Trigger.New){
	     if(rolesToBeChecked.contains(usr.UserRoleId))      
              ur.add (new Contact(
                         FirstName = usr.FirstName,
                         LastName = usr.LastName));
                         
    }
	if(!ur.isEmpty())
        insert ur; 
}


Thanks,
Mohammed

 
UrvikUrvik
Thanks Mohammed for your reply. This is not working. The contact record is not being created upon user record creation.
magicforce9magicforce9
Hi,

I can't think of any specific reason for this not working unless the query is not returning any matching records...Let me add few debug lines and you can setup debug on your user and see whats happening. Try using the code below with debug lines..
 
trigger CreateContact on User (after insert) {    
    List<Contact> ur = new List<Contact>();
    Set<Id> rolesToBeChecked = (new Map<Id, UserRole>([Select Id from UserRole where Name = 'role name1' OR Name= 'role name2'])).keySet();
    System.debug('DEGUB_VARIABLE rolesToBeChecked : ' + rolesToBeChecked);
    for (User usr: Trigger.New){
    	System.debug('DEGUB_VARIABLE : users role Id : ' + usr.UserRoleId);
	     if(rolesToBeChecked.contains(usr.UserRoleId))      
              ur.add (new Contact(
                         FirstName = usr.FirstName,
                         LastName = usr.LastName));
                         
    }
	if(!ur.isEmpty())
        insert ur; 
}
Hope it helps,

Thanks,
Mohammed