0

How do I create a trigger and trigger handler to auto assign a name for custom field on a custom object when a new record is created? The auto-assigned name should be randomly selected from a list of strings.

I have a custom object Cats__c with a custom field Cat_Nickname__c. When a new record is created for the object, I want the code to generate a random value (chosen from a list of strings) for the field. So basically I want to auto assign a nickname to every cat record that is created.

1

I'm using custom settings to enter the names for your cats. Custom setting is of list type and public in scope. I hope you have idea of custom settings.

Now the following trigger will pick up the nicknames from the custom setting sort them and randomize them and select one cute nickname every time when your Cats__c will give birth to a new cute kitten.

trigger giveMyCatCuteName on Cats__c (before insert) {

 // Find all the cat nicknames in the custom setting
 Map<String, CatNames__c> cats = CatNames__c.getAll();

 // Sort them by name
 List<String> nicknames = new List<String>();
 nicknames.addAll(cats.keySet());
 nicknames.sort();

 Integer randomName=Integer.valueOf(Math.floor(Math.random()*nicknames.size()));

 for(Cats__c c: Trigger.new){
       c.Cat_NickName__c=nicknames.get(randomName);

    }

}

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.