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
Cassandra LawsonCassandra Lawson 

Trigger to auto assign field value

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.
Raj VakatiRaj Vakati
 Hi Cassandra , 
The code is here. Please use and let me know if not works. Replace contact object with a custom object.
trigger acct on Contact (before insert,before update) {
    List<String> strs = new List<String>();
    strs.add('Hello') ; 
    strs.add('Hello 1') ; 
    strs.add('Hello 2') ; 
    strs.add('Hello 3') ; 
    
    Integer randomNumber = Integer.valueOf(Math.floor(Math.random()*strs.size()));
    
    for(Contact c: Trigger.new){
        c.FirstName =strs.get(randomNumber);
    }
}

  
Muhammad WasimMuhammad Wasim
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);

    }

}