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
NerdyNerdy 

How to insert data from lookup field with apex controller

Hello Community

I have a custom object MyCustomObj__c which has 2 relashionship lookups on Contact Object. Contact1__c and Contact2__c
How can I insert with apex a record in Contact1__c  ?
Best Answer chosen by Nerdy
Sujeet PatelSujeet Patel
Hii 
Nerdy I think this code will help full for you.
Contact c=new Contact();
c.LastName='Demo';
insert c;

MyCustomObj__c  m=new MyCustomObj__c();
m.Contact1__c=c.id;
m.Contact2__c=c.id;
insert m

 

All Answers

Sujeet PatelSujeet Patel
I hope my answer will help full.
public class demo
{
   public static void test(){
     Contact1__c c=new Contact1__c();
    c.field='value';
   
    insert c;
   MyCustomObj__c obj=new    MyCustomObj__c();
   obj.Contact1=c.id;
  insert obj;

   }

}


​​​​​​​
Raj VakatiRaj Vakati
To add the lookup field .. first you need to inseet the refernce 
and the insert the child like below 
 
account acc = new account(Name ='Test');
 insert acc;
       
      Contact e = new Contact();
e.LastName='Test'
        e.AccountId = acc.id;
        insert e;

Or you can query and assign it also ..like below 

 
account acc  =[Select Id from Account Limit 1 ];
       
      Contact e = new Contact();
e.LastName='Test'
        e.AccountId = acc.id;
        insert e;

 
NerdyNerdy
Hello Patel Sujeet,

When I try to create the contact1__c It gives me this error :  Invalid type: contact1__c  because it's not an object it is just a lookup field on Contact
Sujeet PatelSujeet Patel
Hii 
Nerdy I think this code will help full for you.
Contact c=new Contact();
c.LastName='Demo';
insert c;

MyCustomObj__c  m=new MyCustomObj__c();
m.Contact1__c=c.id;
m.Contact2__c=c.id;
insert m

 
This was selected as the best answer