+ Start a Discussion
Dale WorthingtonDale Worthington 

Creating a contact from a user though a trigger - help please

Hi All

We use an ap within our or that creates users so they can connect though a portal, when these users are made i want to create a contact. The package write the AccountID which the user is associated to into a custom field on the user record, unfortunatly its just text and i cannot use it in the process builder so im trying with an apex trigger. Im getting an error on line 6 where 'for' is mentioned.

I have got an example trigger online but i cannot seem to make it work. If someone could point me in the right direction it would be super. Also keen on any other ideas! :)
 
trigger createAUser on User (after insert) {
    
    List <Contact> ContactInset = new List <Contact> 
    // or whatever your custom object name put instead of Contact
    
    for (User o : Trigger.new) {
        
        
        // here is where you check if User that is being inserted
        // meets the criteria
        //  if (o.Type__c = "X") {  
        
        Contact v = new Contact (); //instantiate the object to put values for future record
        
        // now map User fields to new vehicle object that is being created with this User
        v.FirstName = o.FirstName;
        v.LastName = o.LastName;
        v.Email = o.Email;
        v.Contact_Status__c = "Secondary";
        v.Job_Function__c = "Other";
        v.Job_Level__c = "Administrator";
        v.AccountID = o.AccountId;

        
        //once done, you need to add this new object to the list that would be later inserted. 
        //don't worry about the details for now
        
        ContactInset.add(v);
        
        
        //  }//end if
        
    }//end for o
    
    //once loop is done, you need to insert new records in SF
    // dml operations might cause an error, so you need to catch it with try/catch block.
    try {
        insert ContactInset;    
    } catch (system.Dmlexception e) {
        system.debug (e);
    }
    
}

 
Prosenjit Sarkar 7Prosenjit Sarkar 7
Hi Dale,
There is a simple typo in your code at line number 3.

the line should be like this,
List <Contact> ContactInset = new List <Contact>();

you have missed the brackets while defining ContactInset.

Thanks 
Prosenjit
Dale WorthingtonDale Worthington
Hi Prosenjit,

Thanks for your reponse. Making the changes you suggested allowed me to save the trigger however the overall behaviour was not as expected.  I can see its triggered in the log but there nothing beyond that. Shame :(

I tried this in the process builder but because the 'AccountID' field in the user record is just text which is populated it didnt work, i had hoped by using a tiger i could jsut force that text into a field upon creation of the contact. 

 
Prosenjit Sarkar 7Prosenjit Sarkar 7
PLease check if the trigger is activated or not and let me know if there is another trigger or not.