• swati_seh
  • NEWBIE
  • 0 Points
  • Member since 2013

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies

I'm having issues writing a trigger that will insert a Contact record from information based on the Account.

 

Basically, if it's an account is inserted, I want it to create a Contact.  That part is easy.  The next part that I am having trouble writing is if the account is updated part.   If it's an update, I want it to look to see if there are any Contacts with the Contact_Type__c = General.  If not, then it needs to create a Contact like in the insert portion.  Thought it was simple enough but I can't get it work correctly.  I also need to make sure that this bulk safe since we load accounts nightly.

 

 

I marked the line it's failing on in red.

 

 

 

trigger CreateAccountContact on Account (after insert, after update){

    if(Trigger.isInsert){
    
        List<Contact> ct = new List <Contact>();
        
        for(Account acc : trigger.new){

        Contact c = new Contact(LastName = acc.name,
                        AccountId=acc.id,
                        Fax=acc.Fax,
                        MailingStreet=acc.BillingStreet,
                        MailingCity=acc.BillingCity,
                        MailingState=acc.BillingState,
                        MailingPostalCode=acc.BillingPostalCode,
                        MailingCountry=acc.BillingCountry,
                        Phone=acc.Phone);

        ct.add(c);
        
        }
        
        if(!ct.isEmpty())
            insert ct; 
    }
    
    else{
        
        List<contact> cntsload = new List <Contact>();
        
        for(Account acc : trigger.new){
                List<Contact> cnt = new List<Contact>([select id, Contact_Type__c from Contact where AccountId = acc.id and Contact_Type__c = 'General']);
        
        if(cnt.isEmpty()){

        Contact c = new Contact(LastName = acc.name,
                        AccountId=acc.id,
                        Fax=acc.Fax,
                        MailingStreet=acc.BillingStreet,
                        MailingCity=acc.BillingCity,
                        MailingState=acc.BillingState,
                        MailingPostalCode=acc.BillingPostalCode,
                        MailingCountry=acc.BillingCountry,
                        Phone=acc.Phone);

        cntsload.add(c);
        
        }
        }
        
        if(!cntsload.isEmpty())
            insert cntsload; 
    
    
    }
    
}