+ Start a Discussion
Sindhu AmbarkarSindhu Ambarkar 

When the account record is created contact is created automatically

Hi,

When the account is created contact is created automatically.
trigger childc on Account (before insert) {
List<contact> con=new List<contact>();
    for(Account a:trigger.new)
    {
        contact c=new contact();
        c.Accountid=a.id;
        c.lastname=a.name;
        con.add(c);
    }
    insert con;
}
Please help
Thanks & Regards,
Sindhu Ambarkar.
Best Answer chosen by Sindhu Ambarkar
Pankaj_GanwaniPankaj_Ganwani
Hi,
 
trigger childc on Account (after insert) {
List<contact> con=new List<contact>();
    for(Account a:trigger.new)
    {
        contact c=new contact();
        c.Accountid=a.id;
        c.lastname=a.name;
        con.add(c);
    }
    insert con;
}

You should use after insert instead of using before insert event. Please use above mentioned code to achieve this.

All Answers

Pankaj_GanwaniPankaj_Ganwani
Hi,
 
trigger childc on Account (after insert) {
List<contact> con=new List<contact>();
    for(Account a:trigger.new)
    {
        contact c=new contact();
        c.Accountid=a.id;
        c.lastname=a.name;
        con.add(c);
    }
    insert con;
}

You should use after insert instead of using before insert event. Please use above mentioned code to achieve this.
This was selected as the best answer
Sindhu AmbarkarSindhu Ambarkar
Thanks Pankaj.
In before event and  after event,trigger.new contains the id.What is the difference.Can you explain in better way.
Thanks & Regards,
Sindhu Ambarkar.
Sindhu AmbarkarSindhu Ambarkar
Thanks Pankaj.
 
sandip87sandip87
Hi, 
You should use after Insert trigger on Account obj. before Insert will not work because it will not have the real Account ID for the record beeing inserted (not real because that will be submitted to the database after the transaction completes). 
Well for your concern regarding the ID for Trigger.new on before insert, this is not allowed because you are inserting associated record(s). If there is a failure to parent record for whatever reason, your child records will not get the parent Id (Acc Id in this case). You can check this by putting a debug for Trigger.new Id, break the insertion of account record by some validation rule or another way. Debug will give you one Id for the account in Trigger.new (Though it is not inserted), but you won't be able to find a record with this Id in Salesforce !!
Sandip
Pankaj_GanwaniPankaj_Ganwani
Hi Sindhu,

Please mark it as the best answer if it solves your issue.

Thanks,
Pankaj