+ Start a Discussion
annoyingmouseannoyingmouse 

Trigger to set default Account on Contact

Hi All,

 

This is something of an issue for me at the minute as it's making me pull my hair out.

 

I want all new Contacts to default to a "Public" Account and I've written this trigger:

 

trigger PopulateAccountNameForNewContact on Contact (before insert, before update){
    system.debug(' ************ WORKING HERE ************ ');
    for (Contact contact: Trigger.new){
        try{
            for (Account a :[select id, Name from account where Name = 'Public' LIMIT 1]){
                if (contact.Account == null){
                    contact.Account = a;    
                    system.debug('DEBUG: Update Contact setting Account to ' + a);
                }else{
                    system.debug('DEBUG: The contact is not null - nothing to do');
                }
            }          
        }catch (DMLException e){
            system.debug('contact execution failed: '+ e);
        }    
    }
}

 

It's not working though... any ideas what I'm doing wrong?

 

Cheers in advance,

 

Dom

Best Answer chosen by Admin (Salesforce Developers) 
Gunners_23Gunners_23

Instead of the below line

 

contact.Account = a;  

 

Use the following code 

 

contact.AccountId = a.Id;

All Answers

Gunners_23Gunners_23

Instead of the below line

 

contact.Account = a;  

 

Use the following code 

 

contact.AccountId = a.Id;

This was selected as the best answer
annoyingmouseannoyingmouse

Cheers Gunners,

 

worked a treat!

 

Ta,

 

Dom