+ Start a Discussion
Markey1Markey1 

Insert 18 Digit Contact ID into Contact

This is pretty simple although I am a complete newb to triggers and Apex code. I have a field "Contact18Dig" on the Contact object that I am trying to populate the 18 digit contact id to. Any time a new contact is created or the "Contact18Dig" field is modified, I want the "Contact18Dig" field to populate with the full contact ID. If I create a contact and then edit the record, this code works fine. But, it is not inserting the 18 digit contact upon creating a new contact.

 

Any assitance, guidance, or corrected code examples are much appreciated.

 

trigger ContactID18Digit on Contact (before insert, before update) { for(Contact c : Trigger.new) { if(c.Contact18Dig__c != c.id) { c.Contact18Dig__c = c.id; } } }

 

SuperfellSuperfell
In a before insert trigger there is no id, so for the insert case, you'll need an after insert trigger instead.
S_LieS_Lie
if the trigger is before insert, the ID is not generated yet..
Markey1Markey1

Thank you SimonF and S_Lie for your response. I have changed the code to after insert although I am now receiving an error when creating a new contact. If I edit a field on an existing record, no error is received. The "Contact18Dig" field is editable at the field level as well as the page layout. Is this a record locking issue? Should I be breaking this out into a class and "hooking"? Should I be using "Trigger.old"? Again, I am a complete newb so any help or code assistance is appreciated.

 

Error: Invalid Data. Review all error messages below to correct your data. Apex trigger ContactID18Digit caused an unexpected exception, contact your administrator: ContactID18Digit: execution of AfterInsert caused by: System.Exception: Record is read-only: Trigger.ContactID18Digit: line 7, column 9

 

 

New Code:

trigger ContactID18Digit on Contact (after insert, before update) { for(Contact c : Trigger.new) { if(c.Contact18Dig__c != c.id) { c.Contact18Dig__c = c.id; } } }

 

Markey1Markey1

S_Lie,

 

Any guidance in regards to my last response?