I am creating a new user depending on the existing contact record. Now i want to change the contact record owner to newly created user. below is my trigger. In userList i am getting the newly created user id but i don't know how to map the userid with the contactid.

trigger createUserFromLead on Contact (after insert) {

    List<User> userList = new List<User>();

    List<Profile> profileList = [Select Id from Profile where Name=: 'New Joinee' limit 1];
    for(Contact c: Trigger.New){
            User uObj = new User();
            uObj.Username = c.Email;
            uObj.Email = c.Email;
            uObj.Alias = c.FirstName;
            uObj.LastName = c.LastName;
            uObj.ProfileId = profileList[0].Id;
            uObj.IsActive = true; 
            uObj.TimeZoneSidKey = 'GMT';
            uObj.LanguageLocaleKey = 'en_US';
            uObj.EmailEncodingKey = 'UTF-8';
            uObj.LocaleSidKey = 'en_US';
            //uObj.ContactId = c.Id;



    if(userList.size() > 0){
        insert userList;


One way to do this is with an xref map between the index of the inserted User and the Contact that created it. You'll need recursion control to prevent the Contact update DML from re-executing this trigger's logic and hence an infinite loop.

// test for recursive trigger control here...

map<Integer,Contact> uIxToContactMap = new map<Integer,Contact> ();
for (Contact c: Trigger.new) {
    if (c.ConvertedFromContact__c) {
        userList.add(new User (...));
        uIxToContactMap.put(userList.size()-1,c); // build xref

insert userList;  // add users
Contact[] cUpdList = new List<Contact>();
for (Integer i = 0; i < userList.size(); i++) {  // go thru Users
    Contact c = uIxToContactMap.get(i);  // find the Contact that created it
    Contact cClone = c.clone(true,true);  // avoid updating trigger.new
    cClone.ownerId = userList[i].ID;  // assign ownerId from User.id
    cUpdList.add(cClone);  // add to update list
// enable recursive trigger control here using your favorite framework
update cUpdList;  // updates Contact with new ownerId
// disable recursive trigger control here
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.