+ Start a Discussion

Task triggers Opportunity Updates

I've visited this a couple times in the past but never quite got it figured out. Does anyone have a good example of updating an Opportunity field based upon a Task trigger? I need to change the value of a Opportunity pick list based on the Status of a related Task.

I'm guessing the devil is in the details on this one.  Do you have code that isn't working?  At a high level, my first take is that you could grab the related opportunity from the WhatId field, grab the opportunity, update the picklist value and you're good to go (bulkification required).

If you have code that's doing that, and it's not working, it would be great to take a look at it.
Heres the code I'm working on. What I want to do is update the Stage field in the parent Opportunity from a Task. If a paticular Task is closed then I'll change the Stage. The overall project is more complicated but this is the individual code thats giving me problems. Any thoughts?
trigger UpdateStage on Task (after update) {
Task[] tsk = Trigger.new;

    SET<ID> tskIds = new SET<ID>();
    for (Task t:tsk) {
        if (t.isClosed) {
    Opportunity pO = [SELECT id FROM opportunity WHERE id = : tskIds FOR UPDATE];
    if (pO.StageName != 'Prospect Closed / Lost') {
        pO.StageName = 'Prospect Closed / Lost';
        update pO;


Message Edited by Virturion on 10-27-2008 09:25 AM
Looks like there are a few issues surrounding how you select which records to work with.

* On the Tasks, you are gathering task ids. If you're going to be grabbing opportunities, you probably need to be grabbing WhatId's from the Tasks and not the Task Ids.

* On the Opportunity, you are querying the TaskId's you collected during the first part. This won't work since you're collecting Task Id's.

* On the Opportunity, you are using a " = " operator with a collection. You should be using " IN " instead.

* On the Opportunity, you are assigning the results of a query, a list, to a single object. Right now that's not causing an error since you are collecting TaskIds and not getting any Opportunity hits. You should assign that to some kind of collection.

From a troubleshooting point of view, you might try a System.debug or two in order to display the results of your queries. You can then execute these and view the results. If you do that and aren't seeing the results you know you should, you know you need to go back to the drawing board a bit on your design.

Hope that helps. Cheers.

Did you ever get your code to work? Can you share it?