In Salesforce, every Contact record must be matched to an Account in order to be viewed by your entire organization. Unfortunately, users uploading in new Contacts via data import, or entering a new Contact manually, usually forget to enter in an Account field. Later, when other users search for that Contact, they won’t be able to find it, as Salesforce considers a Contact to be private (and thus not searchable), if it’s not linked to an Account.
Since the Account field on Contacts is standard, we can’t just modify it to make it a Required Field. Oddly, creating a Workflow to specify an Account when one doesn’t exist doesn’t work, for reasons that are a bit of a mystery to me. Enter Triggers: a programmatic way to take some action before or after a record is created, updated, or deleted.
First, create a generic Account that can function as a catch-all. I suggest “Individuals”. Then, use either the Apex Deployment Tool or the Force.com Toolkit for Eclipse to create a new trigger (using those tools will be the subject of future posts).
trigger SetDefaultAccount on Contact (before insert) {
For (Contact nc:Trigger.new) {
If (nc.AccountId == NULL)
nc.AccountId = [select Id from Account where Name = 'Individuals'].Id;
}
}
The code basically says: “Before a new Contact is inserted and if it doesn’t have an Account Id, set the Id to the Account named ‘Individuals’.
In Eclipse, you’ll be prompted to provide some test coverage for the trigger before deploying:
public class testcontact {
static testmethod void mytest1() {
Contact c = new Contact(LastName='test lname');
insert c;
}
}
Awesome! Now you’ll never have to worry about anyone in your organization forgetting to link a new Contact to an Account.
Hat-tip to Mike Rosa @ Salesforce.com for helping me out with this.

Full Feed
Comments
Leave a response
You know your trigger will fail under bulk access, right? (too many SOQL queries). You only need to do the account query once.
As always, Simon is right—the trigger needs to be made bulk-safe. We’ve also made a similar trigger work on Update so if someone blanks out the Account, it will come right back. I’m happy to share the code if you want it.
To bulkify, make the query before the for..loop and hold the id in a variable. Then set the accountid to that variable as you loop through the records.