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
pathi bahubhalipathi bahubhali 

Add the contact to the account record

hi 
Here my requirement is  new account is having already 2 contacts.
when ever a new contact record is created then add that contact to "New account".
 
here i have written trigger.
trigger contrig on Contact (after insert) {
  
    for(contact con:Trigger.new)   
   {
    
       account newacc=[SELECT Id,Name FROM Account WHERE Name = 'new account'];
      con.accountid = newacc.id;
    insert con;
  }
 }

thanks in advance,
kattappa
 
Best Answer chosen by pathi bahubhali
Abhishek BansalAbhishek Bansal
Hi Kattapa,

Using the SOQL in for loops is not a best practice in saleforce so please try to avoid these things in future.
Also when you have to make the updation in the same record that has been inserted or updated than please use before event in the trigger.
I have modifed your trigger code.
Please find below the updated trigger code :
trigger contrig on Contact (before insert) {
	Account newacc = [SELECT Id,Name FROM Account WHERE Name = 'new account'];
	for(contact con:Trigger.new)   
	{   
      con.Accountid = newacc.id;
	}
}

Please let me know if you need more help on this.

Thanks,
Abhishek Bansal.

All Answers

Prad NethasPrad Nethas
Hey Kattappa,

Try to change the event from after to before, it will work, because you are trying to acces the record after insert and update it. And contacts will get created under the account you have queried.
Also better do not put queries in loops.

Hope this will solve your issue.

If it works give kudos to my answer.

Regards
Prad

 
Abhishek BansalAbhishek Bansal
Hi Kattapa,

Using the SOQL in for loops is not a best practice in saleforce so please try to avoid these things in future.
Also when you have to make the updation in the same record that has been inserted or updated than please use before event in the trigger.
I have modifed your trigger code.
Please find below the updated trigger code :
trigger contrig on Contact (before insert) {
	Account newacc = [SELECT Id,Name FROM Account WHERE Name = 'new account'];
	for(contact con:Trigger.new)   
	{   
      con.Accountid = newacc.id;
	}
}

Please let me know if you need more help on this.

Thanks,
Abhishek Bansal.
This was selected as the best answer