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
lainchburylainchbury 

Using an Apex trigger to update the value of a picklist field.

Hello

 

I'm trying to use an apex trigger to update the value of a picklist field on a related object. The trigger will execute when a custom object is inserted and then retrive a list of all the Tasks associated with the custom object.

 

I then want to change the 'Status' field (which is a picklist field) on the tasks.

 

Does anyone have any sample code for changing picklist field values in Apex?

 

Thank you.

Best Answer chosen by Admin (Salesforce Developers) 
GuyClairboisGuyClairbois

a picklist field can be updated the same way as a plain text field.

 

after you queried for the tasks, create a loop to go through them. 

 

in the loop just do

 

task.Status = 'new status' ;

 

and after going through the loop, update the set of tasks.

 

Hope this helps,

Guy 

All Answers

GuyClairboisGuyClairbois

a picklist field can be updated the same way as a plain text field.

 

after you queried for the tasks, create a loop to go through them. 

 

in the loop just do

 

task.Status = 'new status' ;

 

and after going through the loop, update the set of tasks.

 

Hope this helps,

Guy 

This was selected as the best answer
Shashikant SharmaShashikant Sharma

Here is your trigger

trigger UpdateStatus on Account(after insert) {

    
    Set<ID> setaccId = new Set<ID>();
    for(Account acc : trigger.new)
        {
            setaccId.add(acc.Id);
        }
    
    if(setaccId.size() > 0)
        {    
            List<Task> listTask = [Select Status from Task where whoId in: setaccId];
            for(Task t : listTask )
                {
                    t.Status = 'Updated Value';
                }                
                
            //update listTask 
            update listTask;    
        }
}

 

I hope will work for you.

 

 

lainchburylainchbury
Thanks Guy, that's all done now and working fine.
BhaskararaoBhaskararao

I have a Status Field contains "AAAAA",    "BBBBB", "CCCCC","DDDDD".

at this time Status field(Picklist Value)is ""BBBBB"

 

After 10 Days I want to change that "BBBBB" to "CCCCC" automatically 

 

How can i update by using SFDC

GuyClairboisGuyClairbois

No code needed for that. I'd suggest time-based workflow, combined with a field update. See the regular Salesforce documentation or the help function.