i am new to sales-force triggers i need help for writing this trigger i tried to wrote but whenever i am inserting new contact for the same parent the account descriptions is getting over written with the new values

trigger ConaccDescription on Contact (after insert) {
    if(Trigger.isAfter && Trigger.isInsert){
        Set<ID> conID =  new Set<Id>();
        List<account> accounts = new list<account>();
        List<string> descriptions = new list<string>();
        for(contact con:Trigger.new){
            if(con.AccountId != null){
            list<contact> contacts = [SELECT Id,Name,Account.name,Account.description,description from contact where id in :conID]; 
            for(contact c:contacts){
                for(string s:descriptions){
                    account acc = new account();
                    acc.id = c.AccountId ;
                    acc.Description =  string.valueOf(descriptions);
            update accounts;

enter image description here

1 Answer 1


You have queries and DML operations in a loop, both of which are bad. Also, you're querying the records only in the trigger, which would cause the overwriting you've observed. Instead, you'll want to query all related contacts, then update the accounts.

Map<Id, String[]> descriptions = new Map<Id, String[]>();
for(Contact record: Trigger.new) {
  descriptions.put(record.AccountId, new String[0]);
descriptions.remove(null); // Ignore private contacts
for(Contact record: [SELECT Description, AccountId 
                     FROM Contact 
                     WHERE AccountId = :accounts.keySet()]) {
  if(record.Description != null) {
Account[] accounts = new Account[0];
for(Id accountId: descriptions.keySet()) {
    new Account(
      Description=String.join(descriptions.get(accountId),', ')
update accounts;
  • Thank you the code really helped me a lot to solve that problem i was getting nuts to put the logic by myself ... Commented May 29, 2022 at 8:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .