You need to sign in to do that
Don't have an account?
Michael Webb 5
Trigger to create record is creating duplicate records first time saved.
I have a trigger that will create a Ownership Record when a field is populated on the contact. It takes that field and the contact and creates the association and adds it to the related list. It is working pretty well except the first time it runs ie. when the field is empty and I put in a value (lookup from the property object) it creates 2 Ownership records. Every other time it only creates one. I do not want the trigger to run if the field is empty obviously because then it would not be able to create the record. I am not sure what I am doing wrong here. Any help is very much appreciated.
rigger 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;
}
}
}
rigger 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;
}
}
}
<pre>
if ( HelperClass.contactTriggerRan ) return;
contactTriggerRan = true;
</pre>
All Answers
<pre>
if ( HelperClass.contactTriggerRan ) return;
contactTriggerRan = true;
</pre>
if (c.One_Prop_Owned__c == null || c.One_Prop_Owned__c == c.One_Prop_Owned__c){
if (c.One_Prop_Owned__c != oldContact.One_Prop_Owned__c && c.One_Prop_Owned__c != null)
@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;
}
}