You need to sign in to do that
Don't have an account?
Dhiraj Kumar 26
Insert Parent(Account) on creation of Child(Contact) Record
If a contact is not associated with any of the account, I want to create an Account via Trigger .
Basically I want three operations:
1. Insert a Contact record
2. Then Account will be inserted
3. Then link contact to Account
This is my code
trigger createAccount on Contact (before insert) {
List<Contact> conlist = new List<Contact>();
for(Contact c : Trigger.New)
{
if(c.accountId == null)
{
conlist.add(c);
}
}
if(conList.size()>0)
{
List<Account> acclist = new List<Account>();
Map<String,Contact> conmap = new map<String,Contact>();
for(Contact c : conList)
{
String accountName = c.firstname+' '+c.lastname;
Account a = new Account(name=accountname);
accList.add(a);
}
insert accList;
for(Account a : acclist)
{
if(conmap.containskey(a.name))
{
conmap.get(a.name).accountId = a.id;
}
}
}
}
Basically I want three operations:
1. Insert a Contact record
2. Then Account will be inserted
3. Then link contact to Account
This is my code
trigger createAccount on Contact (before insert) {
List<Contact> conlist = new List<Contact>();
for(Contact c : Trigger.New)
{
if(c.accountId == null)
{
conlist.add(c);
}
}
if(conList.size()>0)
{
List<Account> acclist = new List<Account>();
Map<String,Contact> conmap = new map<String,Contact>();
for(Contact c : conList)
{
String accountName = c.firstname+' '+c.lastname;
Account a = new Account(name=accountname);
accList.add(a);
}
insert accList;
for(Account a : acclist)
{
if(conmap.containskey(a.name))
{
conmap.get(a.name).accountId = a.id;
}
}
}
}
try the below trigger,
Regards,
Let us know if this helps :)
Thanks,
Amit Singh