function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Arjun y 7Arjun y 7 

How to add null value to contact lookup in account

Hi All,

I have a requirement to populate the active contact record id in Account object. For this, i have taken a contact lookup in account object. whenever user updates the active field, i have written a trigger to update the contact lookup field in account.

If any user deactivates the contact, then the contact lookup in account object should become empty. I am not able to fulfill this scenario.

Can any one please help me for this requirement.

trigger sample on contact(after insert,after update){
List<Account> accList = new List<Account>();
        List<Account> accUpdateContactPerson = new List<Account>();
        List<Id> contactIdList = new List<Id>();
        Map<Id,Id> ContactAccountIdMap = new Map<Id,Id>();
        for(Contact con:cont){
            if(con.Active__C == true){
        accList = [select Id,Contact__c from Account where Id IN: ContactAccountIdMap.keySet()];

            for(Account acc:accList){
                    acc.Contact__c = contactAccountIdMap.get(acc.Id);
                    acc.Contact__c = null; 
            update accUpdateContactPerson;

You've got a couple of issues with your trigger.   You can actuallly do this without querying the Account object.
trigger sample on contact(after insert,after update) {
    Map<Id, Account> accountsToUpdate = new Map<Id, Account>();

    for (Contact con : {
        Id id = null;

        if (con.Active__c) {
            id = con.Id;

            new Account(
                Id = con.AccountId,
                Contact__c = id

    if (!accountsToUpdate.isEmpty()) {
        update accountsToUpdate.values();
NOTE: This code has not been tested and may contain typographical or logical errors
Arjun y 7Arjun y 7
Hi pcon,

Thanks for the reply.

Yes, it will work for one record. But, i want for bulk records. Can you please let me know is there any way to implement this?

The code I provided for you does work for bulk updates and inserts.  The only caveat is that it will mark the contact on the account based on the last contact that it has.  So if you update 3 contacts and the last two in the list are deactivated then it will set the Contact__c field to null.
Arjun y 7Arjun y 7
Hi pcon,

Thanks for the information.

Suppose, if user wants to deactivate all the contacts in bulk due to some data issue.In this type of case, do we have any workaround in the above code.