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
sreekanth cheerasreekanth cheera 

whenever new contact phone number is 999 then automatically associate the accountid buillingstreet?

Ajay K DubediAjay K Dubedi
Hi Sreekanth,

Please try the below code.

// Apex Class

public class InsertedContact {
    public static void createNewContact(List<Contact> contList)
    {
        List<Account> accountList = new List<Account>();
        accountList = [SELECT Id,Name FROM ACCOUNT WHERE NAME='BuilingStreet'];
        
        if(accountList.size()>0)
        {
            for(Contact con: contList)
            {
                if(con.Phone == '999')
                {
                    con.AccountId = accountList[0].Id;
                    con.LastName = 'With BuilingStreet';
                }
            }
        }
    }
}

// Trigger

trigger createContact on Contact (before insert) {
    
    if(Trigger.IsInsert && Trigger.IsBefore)
    {
       InsertedContact.createNewContact(Trigger.old);
    }
}

Please select it as Best answer if you find it helpful.

Thank You,
Ajay Dubedi
sreekanth cheerasreekanth cheera
InsertedContact.createNewContact(Trigger.old);

If we write trigger.new then the code is working.
Ajay K DubediAjay K Dubedi
Hi Sreekanth,

Yes, it will work for Trigger.New because trigger is firing on before insert.It was my mistake.

Please mark it as best answer if it resolves your problem.

Thank You,
Ajay Dubedi