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.
            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
            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.


You cannot assign the account to a contact based on SObject, you will have to reference the Account's Id to the Contact's AccountId field with a key which is ID here.

If you need to add account in before insert add it like this:

contact.AccountId = defaultAccount.Id; // Errors out here.
  • But the contact is added without any account Ids in the first place. My intention is to set one default account to all the contacts. Can you explain a bit? I just want to query one account with Name = 'Example' (which I did in Line 4). Dec 8 '20 at 8:14
  • Misunderstood your question, changed my code. You will have to assign the ID reference from Account to your Contact. Dec 8 '20 at 8:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.