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
RaoSRaoS 

Apex code to update a custom field on Contact

Hello Gurus ,
I have a custom field(PrimKey) which is type character on Contact. 

1.)I would like to update this field to a unique key combination value for all the existing Contacts using some script.

The value for the first contact processed should be something like 2019ABC00001
The next contact should be updated to 2019ABC00002
The script should generate this unique key in this way for all the contacts.

2.) Generate the same key combination but with different characters (to differentiate from existing contact) for the new contacts using Apex code
This should be a combination of current year followed by ABD followed by 00001
Ex: 2019ABD00001
When the next contact is created it should generate 2019ABD00002.

Let me know how I can achieve these.

Thanks.
Rao
Ajay K DubediAjay K Dubedi
Hi Raos,
Try the following code:
//fetch list of all contacts which are new.
List<Contact> newContactlist = [SELECT id FROM Contact where CreatedDate(=/</>) specifyTheDateHere];


integer i= 1;
List<Contact> updatedList = new List<Contact>();

//Loop through the list
for(Contact c : newContactlist){
    c.PrimKey = date.today().year()+'ABD'+'000'+i;
    updatedList.add(c);
i++;
}
update updatedList;
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi
RaoSRaoS
Hi Ajay, 
Thank you for the script.

Actually there is a size limit for this field. It is 12 character length.

Once "i" reaches 10 the value becomes 2019ABD000010 which will be crossing my field length.

Let me know.

Thanks
Rao
Ajay K DubediAjay K Dubedi
Ok got it !!
Please make following changes in the loop:

for(Contact c : newContactlist){

if(i < 10){
c.PrimKey = date.today().year()+'ABD'+'000'+i; updatedList.add(c);
i++; }
if(i < 20){
c.PrimKey = date.today().year()+'ABD'+'00'+i;
updatedList.add(c);
i++;
}
}

This should now do the job for you.