Question

Hi I am New to salesforce and I need some help in solving a Apex trigger issue.

I tried to create a contract record using trigger on Opportunity. When an Opportunity SatgeName is changed to 'Pending win' the following code creates an Contract record. The issue is when the opportunity is Updated, the code doesn't seem to work. Please let me know where i am going wrong.

Attached is the code.

trigger CreateContract on Opportunity (after insert, before 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 Record.

    try {
        insert conttoinsert;
    } catch (system.Dmlexception e) {
        system.debug (e);
    }

}

Any help is Highly Appreciated.

Thanks

Was it helpful?

Solution

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{}

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top