You need to sign in to do that
Don't have an account?
Dileep Katari
How to Write a trigger which will create as many number of contacts on the account record equal to the value of a number field called count of contacts on account?
If count of contacts has a value 2, 2 contacts should be created on the account inserted, if its 3, 3 contacts should be created on the inserted account.
Can you please help me debug or correct this? receiving null pointer error.
trigger CoCLikeNumberofContacts on Account (before insert) {
List<Contact> conList = new List<Contact>();
Account a = new Account();
integer b = a.Count_of_Contacts__c.intValue();
for(Account a : trigger.new) {
if(b > 0) {
for(integer b = 0; b > 0; b++) {
conList.add(new Contact(Lastname = a.Name, AccountId = a.Id));
}
}
insert conList;
}
}
Can you please help me debug or correct this? receiving null pointer error.
trigger CoCLikeNumberofContacts on Account (before insert) {
List<Contact> conList = new List<Contact>();
Account a = new Account();
integer b = a.Count_of_Contacts__c.intValue();
for(Account a : trigger.new) {
if(b > 0) {
for(integer b = 0; b > 0; b++) {
conList.add(new Contact(Lastname = a.Name, AccountId = a.Id));
}
}
insert conList;
}
}
Try below code and if its working please select best answer,It wiil help to others...
trigger Trigger on Account (after insert) {
List<contact> lst = new List<contact>();
map<id,decimal> ma = new map<id,decimal>();
for(account acc:Trigger.new){
ma.put(acc.id,acc.No_of_contacts__c);
}
if(ma.size()>0 && ma != null){
For(id acid:ma.keySet()){
for(integer i=0;i<ma.get(acid);i++) {
contact cont = new contact();
cont.AccountId = acid;
cont.LastName = 'contact'+i;
lst.add(cont);
}
}
}
if(lst.size()>0 && lst != null)
insert lst;
}
Regards,
ugsfdc
All Answers
Try below code and if its working please select best answer,It wiil help to others...
trigger Trigger on Account (after insert) {
List<contact> lst = new List<contact>();
map<id,decimal> ma = new map<id,decimal>();
for(account acc:Trigger.new){
ma.put(acc.id,acc.No_of_contacts__c);
}
if(ma.size()>0 && ma != null){
For(id acid:ma.keySet()){
for(integer i=0;i<ma.get(acid);i++) {
contact cont = new contact();
cont.AccountId = acid;
cont.LastName = 'contact'+i;
lst.add(cont);
}
}
}
if(lst.size()>0 && lst != null)
insert lst;
}
Regards,
ugsfdc
Greetings to you!
Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.
I hope it helps you.
Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.
Thanks and Regards,
Khan Anas