• Dhiraj Kumar 26
  • NEWBIE
  • -10 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 0
    Replies
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;
                  }
              }
        }

}