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
jsymonds24jsymonds24 

trigger to create an activity when an opportunity reaches a certain stage

I am trying to write a trigger that will create an activity when an opportunity reaches a certain stage.  I want the activity to be assigned to the owner of the opportunity and to be related to the opportunity, but when I try to assign values to the appropriate fields I get 'Field is not writeable' errors.  Here is the code with these fields commented out:

 

--------------------------------------------------------------------------------

trigger CreateActivityAfterClosedWon on Opportunity (after insert, after update) {
 
    List<Task> NewTasks = new List<Task>();
    for (Opportunity opp: Trigger.new){
        if (opp.StageName == '100 - Closed Won - Booked'){
                NewTasks.add(new Task(
                    ActivityDate = Date.today(),
                    //What = opp.Id,
                    //Owner = opp.Owner,
                    Status = 'Closed',
                    Activity_Type__c = 'Project Won',
                    Priority = 'Normal',
                    Subject = opp.Name));
        }
    }

    insert NewTasks;
}

--------------------------------------------------------------------------------------------

 

With these fields commented out, the trigger runs in the sand box and creates activities, but the activities are not related to any object and are assigned to me (because the code ran under my account).

 

Can anybody suggest a solution?


Thanks & Regards,

Jeff

Best Answer chosen by Admin (Salesforce Developers) 
mgodseymgodsey

Try making the following changes:

 

WhatId = opp.Id,
OwnerId = opp.OwnerId,

All Answers

mgodseymgodsey

Try making the following changes:

 

WhatId = opp.Id,
OwnerId = opp.OwnerId,

This was selected as the best answer
jsymonds24jsymonds24
That fixed the problem. Thanks very much.

Best Regards,
Jeff

Jeff Symonds | Salesforce Administrator
Newforma, Inc. | 1750 Elm Street, 10th Floor | Manchester | NH | 03104 | USA
Office: +1.603.625.6212 x378 | Fax: +1.603.218.6145 | www.newforma.com