+ Start a Discussion
Amanda HosseiniAmanda Hosseini 

Opportunity to Trigger Tasks

I am looking to have tasks triggered based on line items within an opportunity when the opportunty is closed. 
John PipkinJohn Pipkin
Amanda, 

Please be more specific in what you are wanting the trigger to do. Here's a rough outline:
Trigger doStuff on Opportunity(after update){
	Set<ID> oppids = new Set<ID>();

	for(Opportunity currentO :Trigger.new){
		Opportunity oldO = Trigger.oldMap.get(currentO.Id);

		if(currentO.StageName != oldO.StageName && currentO.StageName == 'Closed')
			oppids.add(currentO.Id);
	}

	if(!oppids.isEmpty()){
		OpportunityLineItem oli = [Select Id,Opportunity from OpportunityLineItem
								where Opportunity in :oppids];
	}

	List<Task> newTasks = new List<Task>();

	for(Opportunity currentO :Trigger.new){
		for(OpportunityLineItem olis :oli){
			if(currentO.Id == olis.Opportunity){
				if(/*other conditions for line items*/){
					Task t = new Task();
					t.WhatId = currentO.Id;
					//set other field values
					newTasks.add(t);
				}
			}
		}
	}

	if(!newTasks.isEmpty){
		insert newTasks;
	}
}

 
Amanda HosseiniAmanda Hosseini
For example, if an opportunity has a line item for "on-site training" I would like a tast to trigger when the opportunity is won
John PipkinJohn Pipkin
This should get you started:
Trigger doStuff on Opportunity(after update){
	Set<ID> oppids = new Set<ID>();

	for(Opportunity currentO :Trigger.new){
		Opportunity oldO = Trigger.oldMap.get(currentO.Id);

		if(currentO.StageName != oldO.StageName && currentO.StageName == 'Closed-Won')
			oppids.add(currentO.Id);
	}

	if(!oppids.isEmpty()){
		OpportunityLineItem oli = [Select Id,Opportunity, Nme from OpportunityLineItem
								where Opportunity in :oppids];
	}

	List<Task> newTasks = new List<Task>();

	for(Opportunity currentO :Trigger.new){
		Opportunity oldO = Trigger.oldMap.get(currentO.Id);

		if(currentO.StageName != oldO.StageName && currentO.StageName == 'Closed-Won'){
					
			for(OpportunityLineItem olis :oli){
				if(currentO.Id == olis.Opportunity){
					if(olis.Name == 'on-site training'){
						Task t = new Task();
						t.WhatId = currentO.Id;
						//set other field values
						newTasks.add(t);
					}
				}
			}
		}
	}

	if(!newTasks.isEmpty){
		insert newTasks;
	}
}

You may need to change/add fields or Stage Names to fit your Salesforce setup.