function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Mahesh KGMahesh KG 

Create Account and link the Contact to the created Account

Hi Team,

can you help me linking the contact to the created account?

i have created a new APEX for creating an account. i need to create a contact and link the contact to the account.

Can you please help me with this.

i also tried creating the Seprate Contact object. but i need to know how to link Account to Contact.
shaik murthujavalishaik murthujavali
Hi Mahesh,
For linking contact to account- first you need to insert an account into object so then you can query Id of that record and you create a contact for that perticular account.
Account a = [select Id, Name from Account where Name = ''Shaik'];
Contact c = new Contact();
c.LastName = 'somename';
c.AccountId = a.Id;
insert c;

Hope it helps.
If you provide your code, it helps us to provide you a better sollution.
Let me know if it works/any help needed.

Shaik Murthujavali
Mahesh KGMahesh KG
Thank you for the reply. Please find the below code,

global static ID createAccount(String name,String parent, String accountMgr,String setUpFee,String lastName) {
//Create the account object        
Account restAcc = new Account(
        insert restAcc;
// i need to create the Contact object for the above Account created.
                                       Contact restCont = new Contact(LastName=lastName );
                                       insert restCont;
        return restAcc.Id;

can i create contact right after the creation of the account? if so let me know how to do it the above code?
Ajay K DubediAjay K Dubedi
Hi Mahesh,

Use the below code get the solution:
Account accountObj = new Account();
insert accountObj;

Contact contactObj = new Contact();
contactObj.LastName = 'xyz';
contactObj.AccountId = accountObj.Id;
insert contactObj;
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Ajay Dubedi