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
Aashi AditiAashi Aditi 

trigger to create a new account on basis of first name and last name of contact

insertaccount: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.insertaccount: line 14, column 1

trigger insertaccount on Contact (after insert,after update) 
{
   set<id> accountIdList = new Set<id>();  
    for(contact con : Trigger.new)  
    {  
        accountIdList.add(con.accountid);  
    }  

    Map<Id,account> mapVar = new Map<Id,account>([SELECT id,name
                                                  FROM account WHERE Id IN : accountIdList]);

    for(contact cont : Trigger.new)
    {
            mapVar.get(cont.accountid).name = cont.firstname + cont.LastName;

    }
    update mapVar.values();
}

when I create a new contact so on basis of first name and last name of contact we have to create new account.
CharuDuttCharuDutt
Hii Aashi Aditi
Try The Following Code
trigger test on Contact (before insert) {

    
    List<Contact> needAccounts = new List<Contact>();
    for (Contact c : trigger.new) {
        if (String.isBlank(c.accountid)) {
            needAccounts.add(c);
        }
    }
    
    if (needAccounts.size() > 0) {
        List<Account> newAccounts = new List<Account>();
        Map<String,Contact> contactsByNameKeys = new Map<String,Contact>();
       
        for (Contact c : needAccounts) {
            String accountName = c.firstname + ' ' + c.lastname;
            contactsByNameKeys.put(accountName,c);
            Account a = new Account(name=accountName);
            newAccounts.add(a);
        }
        insert newAccounts; 
    }
    

}
Please Mark it As Best if it Helps
Thank You
Danish HodaDanish Hoda
hi Aditi,
My question before I give you the working code - if you want to create a new Account, why are you querying for the Account records?