Skip to main content
3 of 4
Changed the code and deleted comments that were unreadable.

Trigger for creating a object with association

We have a field on the Contact form called One Property Owned. This field will be updated in a list view so that one person can go through all of them in a fell swoop. There are two other custom objects one named Property, this is the lookup on the contact. They lookup the property name and it associates. In order to have a one to many association we have another object called Ownership, very simple it has the contact as a lookup and the Property as a lookup then puts them in a related list. So I need to create a trigger when the property lookup field One Property Owned, that will create an ownership object with the property in the looking and the contact associated. I have written quick ones to create cases, off an account but that is about it.

Below is what I have so far:

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

The first time it runs it adds 2 Ownership records every other time when I change that field it only adds one. I am not sure why it is adding 2 the first time.

Thank you!