triggerssalesforceapexsoqlsfdc

Apex trigger to insert record in a related custom object based on insert on contact


I have a custom object called 'contact relationship' which has lookup to contact and i have added a custom field of type checkbox called 'relationship' in contact. I want to write a trigger which adds a record in contact relationship every time a record is added in contact if the relationship checkbox value is true. This is what i have done, but it's not working.

trigger ContactRelationshipTrigger on Contact (after insert) {    
    List<Contact_Relationship__c> crl = new List<Contact_Relationship__c>();
    List<Contact> cl = new List<Contact>();
    for(contact con: trigger.new){
        if(con.Relationship__c == true){
            Contact_Relationship__c cr = new Contact_Relationship__c();
            cr.Contact__c=con.Id;
            cr.Name='Rel to--' + con.Name;
            crl.add(cr);
        }       
    }      
    insert crl;
} 

When i insert a new contact record no contact relationship record is being created.


Solution

  • Your Code looks to be accurate to me, so you should check that your trigger is active. On the Trigger edit page there is an "Is Active" checkbox that you can use to inactivate or activate a trigger. Make sure that it is checked.

    Also the contact name is a compound field so to get the name accurately you need to use

     cr.Name='Rel to--' + con.FirstName +' '+ con.LastName;