【问题标题】:Create Contract Record when Opportunity stage is Updated机会阶段更新时创建合同记录
【发布时间】:2014-03-11 04:09:05
【问题描述】:

您好,我是 salesforce 的新手,我需要一些帮助来解决 Apex 触发器问题。

我尝试使用机会上的触发器创建合同记录。当 Opportunity SatgeName 更改为“Pending win”时,以下代码将创建一个合同记录。问题是当机会更新时,代码似乎不起作用。请让我知道我哪里出错了。

附上代码。

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);
    }

}

非常感谢任何帮助。

谢谢

【问题讨论】:

    标签: triggers salesforce apex


    【解决方案1】:

    通常您的代码似乎没问题,但请尝试以下代码。我将触发规则从 before update 更改为 after update 并删除了 try..catch 语句,因为它会在出现异常时向您隐藏信息。

    如果您的代码有任何问题,您可以获得: 1.我们在触发器中定义的CommonException,用于插入记录不存在的情况 2. System.DMLException 可能在旧版本中被捕获。如果出现这些错误,请在评论中分享。

    请注意,这不是生产代码,此代码仅用于测试目的

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

    【讨论】:

    • 嗨 Pavel,感谢您的修改,现在它按预期工作。添加异常后,现在我收到其他错误消息,例如“必填字段帐户缺少数据”所以我修改了代码 a位和 con.AccountId = opp.AccountId;这解决了我的问题。再次非常感谢:)
    猜你喜欢
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多