Hello and thank you for your time.
I have created a trigger on an opportunity that 'should' only run my methods if the stageName = 'PO IN(100%) and a contract is not already created.. as well if certain fields are not null. I get I should do my error checking on the if(trigger.isbefore) and then run my actual methods on the if(trigger.isafter) I am just confused on how I can :
- Disregard any updated opportunity that doesn't meet the criteria of 'PO In 100%'
- Make sure the trigger.old isnt already 'PO In 100%'
- If there are errors (fields are null or a child contract exists) do an addError() but allow the other triggers to run.
So far, I know how to get the opportunities and add them to a list (and put a child quote id if it exists)
List<Id> oppIds = new List<Id>();
List<ServiceContract> SContract = new List<ServiceContract>(); // List that will contain all the new Service Contracts that need to be added
for(Opportunity opp:Trigger.new){
if(Trigger.oldMap.get(opp.id).StageName != 'PO In (100%)' && opp.StageName == 'PO In (100%)') //This should take care of my first & second Step
oppIds.add(opp.Id);
}
List<Opportunity> oppsFromDb = [SELECT
Id, StageName, name, Accountid, owner__c, end_user_contact__c, RecordTypeId, OwnerId,
(SELECT Id FROM Service_Contracts__r), (SELECT Id From Quotes)
FROM
Opportunity
WHERE
Id IN:oppIds
];
Now I imagine is the time to use the before Update
if(Trigger.isBefore){
for(Opportunity verifyOpps: oppsFromDb){
if(verifyOpps.Service_Contracts__r.size() != 0) { //A contract child exists
verifyOpps.addError('A contract already exists, cannot create a new contract.');
}
//.... other error checking code
verifyOpps.save() // I have no idea how to save the record..
}
}
else if(Trigger.isAfter){
for(Opportunity GoodOpps: oppsFromDb){
// create a contract using the opp variables and other calculations
SContract.add(the_Contract);
}
}
insert SContract;
If a contract does exist it should run the opp.addError. Does this mean i need to do an else and put the ones without errors in a new list, so only they go into the isafter trigger?
And by just doing opp.addError, does it automatically give the error or do i have to do something else for it to go back into the db? (Sorry if this is confusing).
Does this code make sense at all? Or am I doing this very wrong :)
Thanks again for your time.