I'm trying to use an Apex trigger to associate Account.Name
to a Contact
from a community form. Here is my trigger,
trigger ContactBeforeInsert on Contact (before insert, after insert) {
String USER_DOMAIN = '@example.com';
Account defaultAccount = [SELECT Id, Name FROM Account WHERE Name = 'Example' LIMIT 1];
List<User> users = new List<User>();
List<Contact> updatedContacts = new List<Contact>();
Profile communityProfileId = [SELECT Id FROM Profile WHERE Name = 'Customer Community User' LIMIT 1];
if (Trigger.isInsert && defaultAccount != null && Trigger.New[0].registerAs__c != null) {
if (Trigger.isBefore) {
for (Contact contact : Trigger.New) {
contact.Account.Name = defaultAccount.Name; // Errors out here.
updatedContacts.add(contact);
}
insert updatedContacts;
}
else if (Trigger.isAfter && !updatedContacts.isEmpty()) {
for (Contact contact :updatedContacts) {
User user = new User(
ContactId = contact.Id,
Username = contact.FirstName + USER_DOMAIN,
LastName = Contact.LastName,
Email = contact.Email,
Alias = contact.FirstName,
TimeZoneSidKey = 'GMT',
LanguageLocaleKey = 'en_US',
EmailEncodingKey = 'UTF-8',
LocaleSidKey = 'en_US',
ProfileId = communityProfileId.Id,
isActive = true
);
Users.add(user);
}
insert Users;
}
}
}
But when I create a contact from the form, I get an error ContactBeforeInsert: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.ContactBeforeInsert: line 17, column 1
.
Line 17 is contact.Account.Name = defaultAccount.Name;
. I have verified that the defaultAccount
is not null
. If I run the same query in the developer console, I do see my account fetched. What's wrong here? I am new to Salesforce and Apex and I am dealing with this issue for the past one day.