0

I have a Custom Field on the Contact Object called UserId__c. When a Contact Record is Created I need to check other Contact Records for their UserId__c value to prevent duplicates. The initial value will populate from NULL to the Contact's FirstName, if there is already a UserId__c field value of a certain FirstName(such as Bob) then the value should be populated as FirstName + LastName, if there is already a UserId__c field value of that particular FirstName + LastName(such as BobSmith) then the UserId__c value should be FirstName + LastName + MailingZipCode(such as BobSmith85340).

trigger UserIDpop on Contact (before insert) {
if( ISBLANK(userid__c), userid__c = LastName,
   if( userid__c = LastName, userid__c = FirstName + LastName,
      if( userid__c = FirstName Last Name, userid__c = FirstName + LastName + MailingZipCode
        )
     ), ,
  ) }
2
  • @Alex Tennant, you had an answer that somewhat built something like this but I am still having problems re-creating itm salesforce.stackexchange.com/questions/49654/… . Do you think you can help with this one? Jul 12, 2019 at 6:34
  • What is your specific question? Your code is not valid Apex. Please edit your original post to include more details about the issues or questions you have. Jul 12, 2019 at 19:37

1 Answer 1

1

Here is the content of the trigger you need to set:

Set<String> alreadyTakenNames = new Set<String>();
List<Contact> existingContacts = new List<Contact>();
existingContacts = [SELECT Id, UserId__c FROM Contact];

for (Contact contact_i : existingContacts) {
    alreadyTakenNames.add(contact_i.UserId__c);
}

for (Contact contact_i : Trigger.NEW) {
    if (!alreadyTakenNames.contains(contact_i.FirstName)) {
        contact_i.UserId__c = contact_i.FirstName;
    } else if (!alreadyTakenNames.contains(contact_i.FirstName + contact_i.LastName)) {
        contact_i.UserId__c = contact_i.FirstName + contact_i.LastName;
    } else {
        contact_i.UserId__c = contact_i.FirstName + contact_i.LastName + contact_i.MailingPostalCode;
    }

    alreadyTakenNames.add(contact_i.UserId__c);
}

I haven't found MailingZipCode as standard field, so I set it as MailingPostalCode. However, it is up to you to change anything here.

If you have any questions, please, feel free to comment.

1
  • Thank you @Mariia Illarionova for answering this so quick! I will plug this in today and reply back with my findings... excited :D Jul 12, 2019 at 15:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .