+ Start a Discussion
Ashok S 7Ashok S 7 

I want to know how to insert a records in 2 custom objects by using custom controller and visual force page those two objects have lookup relation ship plesase tell i am new to salesforce

Hai Guys.
I want to know how to insert a records in 2  custom objects by using custom controller and visual force page those two objects have lookup relation ship plesase tell i am new to salesforce
Sameer PrasonnSameer Prasonn
Hi Ashok,

you can insert a record into 2 object via custom controller. lets take two object A and B. A is having lookup field which take B type of object.

First approach,which is the simplest one:
//Create B object Instance
B__c bObj=new B__c();
//populate the data for B's Fields
bObj.Field1__c=Some Value;
........

//Create A Object
A__c aObj=new A__c();
//populate the data for A's Fields
aObj.Field1__c=Some Value;
........

//insert B Object First
insert bObj;

aObj.lookupField__c=bObj; //assigning value to B's Lookup Field
insert aObj;
make sure first we need to insert the object which is used in lookup field. since we require the value object which has same type of lookup field..

Second approach, in which we can use single insert statement for both the object as following
Account acc=new Account(Name='Sameer', Master_Id__c='SA');
Contact cont=new Contact(FirstName='Sameer', LastName='Barath', Account=new Account(Master_Id__c='SA'));
 
insert new List<Sobject>{acc, cont};
in this Approach we use an external ID(Master_Id__c)  to relate the lookup field.

Hope this resolve your query. Please mark this as best answer if it resolve the query.