在自定义对象上编写触发器

时间:2014-11-10 18:34:28

标签: triggers insert salesforce

我在联系人上有一个名为One_Prop_Owned__c的字段,用户正在视图列表中更新。一旦更新并保存,我需要一个触发器来创建一个名为Ownership的新对象,即McLabs2__Ownership__c。只需要填充两个字段。

是否正在创建此所有权的联系人。所有权表单上的字段为McLabs2__Contact__c,即在One_Prop_Owned_c字段中输入的属性字段。

正如你所知,我在编写触发器方面非常环保。以下这个不起作用,我不知道从哪里开始。非常感谢任何帮助。

   trigger PropOwned on Contact (after update) {
        for (Contact c : Trigger.new){
        McLabs2__Ownership__c ownNew= new McLabs2__Ownership__c();
        Contact oldContact = Trigger.oldMap.get(c.id);
        if (c.One_Prop_Owned__c != oldContact.One_Prop_Owned__c)
        if (c.One_Prop_Owned__c == null || c.One_Prop_Owned__c == c.One_Prop_Owned__c){
        ownNew.McLabs2__Contact__c = c.id;
        ownNew.McLabs2__Property__c = c.One_Prop_Owned__c;
        insert ownNew;
        }
    }
}

嗯,我能够修复触发器,有点工作流程,我可以解决问题。但是,我现在在编写测试类时遇到了问题。这就是我所说的触发器覆盖率为0%。

@isTest
public class TestOwnership {
    static testMethod void ownershipCreator() {
     McLabs2__Ownership__c ownNew= new McLabs2__Ownership__c();
     ownNew.McLabs2__Contact__c = 'Michael Webb';
     ownNew.McLabs2__Property__c = '131 West 33rd Street';
     insert ownNew;
     }
    }

1 个答案:

答案 0 :(得分:0)

尝试以下代码

trigger PropOwned on Contact (after update) {
    // create a list of new records which should be inserted in the Database
    List<McLabs2__Ownership__c> ownerships = new List<McLabs2__Ownership__c>();
    for (Contact c : Trigger.new) {
        Contact old = Trigger.oldMap.get(c.id);
        if (c.One_Prop_Owned__c != old.One_Prop_Owned__c) {
            McLabs2__Ownership__c ownership = new McLabs2__Ownership__c();
            // This condition is absolutely unuseful because statement 'c.One_Prop_Owned__c == c.One_Prop_Owned__c' will always return true
            // if (c.One_Prop_Owned__c == null || c.One_Prop_Owned__c == c.One_Prop_Owned__c) {
                ownership.McLabs2__Contact__c  = c.id;
                ownership.McLabs2__Property__c = c.One_Prop_Owned__c;
                ownerships.add(ownership);
            // }
        }
    }
    if ( !ownerships.isEmpty()) { // check that we have records to insert
        insert ownerships;
    }
}

如果您对此代码有任何错误,请将其发布为对我的回答的评论。