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
richfer_rightrichfer_right 

how to auto-assign color values to a field when a new record is created?

I have created a text field in a custom object. I want to update the field value with color values everytime when a record is created 

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

I see you are a developer of few words.

 

The following code snippet assumes the colours are stored in the apex class.  If not, you'll need to retrieve them from wherever.  It also assumes the sobject type is Contact and the field is 'Colour__c' - replace as appropriate.

 

This method should be called from a before insert trigger, as that way it can change the records before they are committed to the database:

 

private List<String> colours=new List<String>{'red', 'green', 'blue', 'yellow', 'purple', 'orange', 'black'};


public void setColors(List<Contact> conts)
{
   for (Contact cont : conts)
   {
      cont.Colour__c=colours[(Math.random().*colours.size()).intValue()];
   }
}

 

All Answers

bob_buzzardbob_buzzard

Can you clarify your use case.  Are you looking to assign the same text to each new record?  If so, you can look at using a formula to specify a default value for the field.

richfer_rightrichfer_right

No, have to assign different color values to each records

bob_buzzardbob_buzzard

Tell me more - are you round-robin assigning from a pool of colours, or is it random?

richfer_rightrichfer_right

It is to be assigned randomly to the field 

 

bob_buzzardbob_buzzard

I see you are a developer of few words.

 

The following code snippet assumes the colours are stored in the apex class.  If not, you'll need to retrieve them from wherever.  It also assumes the sobject type is Contact and the field is 'Colour__c' - replace as appropriate.

 

This method should be called from a before insert trigger, as that way it can change the records before they are committed to the database:

 

private List<String> colours=new List<String>{'red', 'green', 'blue', 'yellow', 'purple', 'orange', 'black'};


public void setColors(List<Contact> conts)
{
   for (Contact cont : conts)
   {
      cont.Colour__c=colours[(Math.random().*colours.size()).intValue()];
   }
}

 

This was selected as the best answer