Skip to main content
2 of 4
added 650 characters in body
Matt Lacey
  • 25.8k
  • 7
  • 68
  • 153

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)
        McLabs2__Ownership__c newOwn = new McLabs2__Ownership__c();
    
      ownNew.McLabs2__Contact__c = c.id;
      ownNew.McLabs2__Property__c = c.One_Prop_Owned__c;
      insert ownNew;
    }
  }
}

It is adding two records though, and when I clear out a record it tries to run again but can't because the info is not there.