+ Start a Discussion
Mohit Kumar SinghalMohit Kumar Singhal 

how to insert contact in account using apex

I have account and contact standard object . I want to insert data in account and contact object together using apex. contact details should be inserted into account . Please help me out
bhanu_prakashbhanu_prakash
Hi Mohit 
Mark as best answer, If it resloves !!​
check these below code 
try {
    Account acct = new Account(Name='SFDC Account');
    insert acct;

    // Once the account is inserted, the sObject will be 
    // populated with an ID.
    // Get this ID.
    ID acctID = acct.ID;

    // Add a contact to this account.
    Contact con = new Contact(
        FirstName='Joe',
        LastName='Smith',
        Phone='415.555.1212',
        AccountId=acctID);
    insert con;
} catch(DmlException e) {
    System.debug('An unexpected error has occurred: ' + e.getMessage());
}

more info : https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_dml_examples_insert_update.htm​

Mark as resloved if it helps :) :)
Thanks, 
Bhanu Prakash
visit ForceLearn.com
Bhargavi TunuguntlaBhargavi Tunuguntla
Hi Mohit,

Do you need contact details to be updated in the created account after account and contact insertion? -- just a clarificatioon

Thanks
Bhargavi
Raj VakatiRaj Vakati
try {
    Account acct = new Account(Name='SFDC Account');
    insert acct;


    // Add a contact to this account.
    Contact con = new Contact(
        FirstName='Joe',
        LastName='Smith',
        Phone='415.555.1212',
        AccountId=acct.id);
    insert con;
} catch(DmlException e) {
    System.debug('An unexpected error has occurred: ' + e.getMessage());
}

 
Navneet KamatNavneet Kamat
try {
    // Insert Account records
Account acct = new Account(Name = 'SF-Account', BillingCity = 'Bangalore');
insert acct;

// Insert Contact records
Contact con= New Contact(lastName='Business Account ', AccountId=acct.Id);
insert con;
}

catch(DmlException e) {
    System.debug('An unexpected error has occurred: ' + e.getMessage());
}