You need to sign in to do that
Don't have an account?
Nathan Aziz
APEX Trigger Opportunity Won creates new Custom Object
Hey guys I came across this trigger that says it will do just exactly what I needed it to do but with a few changes to do I've modified it so that a new custom object is created when the Opoortunity is won.
I'm running this in Sandbox and can't seem to figure out why the trigger isn't activating.
Basically:
I have a custom object Sponsorship and I want a new sponsor to be created when an Opportunity is won and the appropriate fields to be inserted as well.
Right now it should just create the new object with the name and and account taken from the opportunity. But nothing happens. Any ideas?
I'm running this in Sandbox and can't seem to figure out why the trigger isn't activating.
Basically:
I have a custom object Sponsorship and I want a new sponsor to be created when an Opportunity is won and the appropriate fields to be inserted as well.
trigger createSponsorOnOpportunityWon on Opportunity (after insert) { List <Sponsorship__c> sponsToInsert = new List <Sponsorship__c> (); // or whatever your custom object name put instead of Sponsorship__c for (Opportunity o : Trigger.new) { // here is where you check if opportunity that is being inserted //meets the criteria if (o.StageName == 'Closed Won'){ Sponsorship__c s = new Sponsorship__c (); //instantiate the object to put values for future record // now map opportunity fields to new vehicle object that is being created with this opportunity s.Name = o.Name; // and so on so forth untill you map all the fields. s.Sponsor_Account__c = o.AccountId; //once done, you need to add this new object to the list that would be later inserted. //don't worry about the details for now sponsToInsert.add(s); }//end if }//end for o //once loop is done, you need to insert new records in SF // dml operations might cause an error, so you need to catch it with try/catch block. try { insert sponsToInsert; } catch (system.Dmlexception e) { system.debug (e); } }
Right now it should just create the new object with the name and and account taken from the opportunity. But nothing happens. Any ideas?
All Answers
When you create a new opportunity and save it, what is the StageName at that point of time? As far as I think, when we create a new opportunity, we don't set the StageName to 'Closed Won'. Change the trigger event from 'after insert' to 'after update'. Or, if you want 'Sponsorship__c' records to be created only on insert of Opportunity, make sure StageName is 'Closed Won' at the time of creation.
Let me know if it works.
Thanks
Abhijeet
Even with the original code, creating an opportunity with stage at closed won it does not create a new sponsorship.
You helped me realized I had required fields within the custom sponsorship object.
I've updated them accordingly and it works.
Thanks again!
Any help would be appreciated!