In common your code seems ok, but try code below. I changed the trigger rule from before update
to after update
and removed try..catch
statement because it hides information from you in case of rising exception.
if you have any troubles with your code you can get: 1. CommonException which we defined in the trigger for case when records for insertion doesn't exist 2. System.DMLException which might be catched in old version. If these error will appears please share it in comment.
Please note that this is NOT a production code, this code just for testing purposes
trigger CreateContract on Opportunity (after insert, after update) {
List<Contract> conttoinsert = new List<Contract>();
for (Opportunity opp : Trigger.new) {
// Create contract record only when the Stage is Updated to "Pending Win"
if (opp.StageName == 'Pending win') {
Contract con = new Contract();
con.Opportunity_Name__c = opp.id;
con.Account = opp.Account;
con.CurrencyIsoCode = opp.CurrencyIsoCode;
conttoinsert.add(con); // For Bulk processing of the Records.
} //end if
} // End of For
// Inserting the New Contract Records if these records exist
if ( !conttoinsert.isEmpty()) {
insert conttoinsert;
} else {
throw new CommonException('There are no records for insertion');
}
// define own implementation of Exception
public class CommonException extends System.Exception{}
}