You need to sign in to do that
Don't have an account?
vikas chand 18
Trigger Not proper work on Bulk Data
Hi Developers,
I am write a trigger on Contact Object. trigger work on single record but on bulk data its not working properly.
My code is Here
Thanks in advance
I am write a trigger on Contact Object. trigger work on single record but on bulk data its not working properly.
My code is Here
trigger UpdateContactName on Contact (before insert){ set<id> setAccountId=new set<id>(); if (Trigger.isAfter) { if (Trigger.isInsert) { for(contact con : Trigger.new){ if(con.accountId != null){ setAccountId.add(con.AccountId); } list<string> conId = new list<string>(); for(contact c : [select id, FirstName, lastName from contact where AccountId IN : setAccountId]){ conId.add(c.Id); } for(contact cont : trigger.new){ cont.FirstName = ''; cont.lastName = ''; cont.FirstName = 'Pr'; cont.lastName = string.valueof(conId.size()); } } } } }Any one can correct my code or any suggetions
Thanks in advance
there are some suggestions for you--
1. Never fire any query inside the for loop, this is not the best practice.
2. If you want to update the record of same object, write the trigger in 'IsBefore' action and for other object record use 'IsAfter' acton.
3. Pass all the action in the trigger parameter.
4. Try to write a helper class for the trigger so that you can use the methods in the other class.
After assuming your recuirment I adjust your code----
trigger UpdateContactName on Contact (before insert) {
set<id> setAccountId=new set<id>();
list<string> conId = new list<string>();
if (Trigger.isBefore) {
if (Trigger.isInsert) {
for(contact con : Trigger.new) {
if(con.accountId != null) {
setAccountId.add(con.AccountId);
}
}
for(contact c : [select id, FirstName, lastName, AccountId from contact where AccountId IN : setAccountId]){
conId.add(c.Id);
for(contact cont : trigger.new) {
if(cont.AccountId != Null && c.AccountId == cont.AccountId) {
cont.FirstName = 'Pr';
cont.lastName = string.valueof(conId.size());
}
}
conId.clear();
}
}
}
}