Setting a Default Account Using Triggers

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 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 {
		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 @ for helping me out with this.

blog comments powered by Disqus