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
    Use singular names!
    – Adrian Larson
    Commented Jun 23, 2017 at 20:37

1 Answer 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>();

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

 for(Cats__c c: Trigger.new){



You must log in to answer this question.

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