+ Start a Discussion
inbox outbox 7inbox outbox 7 

We can do the below code with LIST as well but that would give us an error whenever we are INSERTing more than 1 Contact and so we used MAP.

Whenever a contact is inserted, if that contact is associated with an account, then update that account name from this  newly inserting contact name. It has to be bulkified.  If the contact name is "John", then the associated account's name should also be "John:

public Contact trigger updateAccount (AFTER INSERT){

Map<Id, Account> accountList = New Map<Id, Account> ();


for(Contact con: Trigger.New){

   if(con.AccountId){

    Account acc = New Account();
    acc.Name = con.LastName;
    acc.Id = con.AccountId;
    accountList.put(acc.Id, acc);

   }
}
UPDATE accountList.values();
}

I would like to know why we would get an error if we use LIST in production and that we have to use either MAP or SET.
Best Answer chosen by inbox outbox 7
mukesh guptamukesh gupta
Hi ,

Your code is correct can you please check size of map and pelase share  error that's you are facing
 
public Contact trigger updateAccount (AFTER INSERT){

Map<Id, Account> accountList = New Map<Id, Account> ();


for(Contact con: Trigger.New){

   if(con.AccountId){

    Account acc = New Account();
    acc.Name = con.LastName;
    acc.Id = con.AccountId;
    accountList.put(acc.Id, acc);

   }
}

if(accountList.size() > 0)
   UPDATE accountList.values();
}
if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh 

 

All Answers

Sai PraveenSai Praveen (Salesforce Developers) 
Hi,

Can you also share the code with List so experts can help you why the issue is with the List and why not with the map.

Thanks
 
inbox outbox 7inbox outbox 7
Sai Praveen, 

All we have to do is replace map with list and add map methods. 


public Contact trigger updateAccount (AFTER INSERT){

List< Account> accountList = New List<Account> ();


for(Contact con: Trigger.New){

   if(con.AccountId){

    Account acc = New Account();
    acc.Name = con.LastName;
    acc.Id = con.AccountId;
    accountList.add(acc);

   }
}
UPDATE accountList ;
}
mukesh guptamukesh gupta
Hi ,

Your code is correct can you please check size of map and pelase share  error that's you are facing
 
public Contact trigger updateAccount (AFTER INSERT){

Map<Id, Account> accountList = New Map<Id, Account> ();


for(Contact con: Trigger.New){

   if(con.AccountId){

    Account acc = New Account();
    acc.Name = con.LastName;
    acc.Id = con.AccountId;
    accountList.put(acc.Id, acc);

   }
}

if(accountList.size() > 0)
   UPDATE accountList.values();
}
if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh 

 
This was selected as the best answer