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
Mansoor S 5Mansoor S 5 

how to insert lookup field value in apex class..

How to give values to lookup fields in apex class..like to give account name in opportunity object using apex class.

public opportunity op= new opportunity();
op.account='Burlington Textiles Corp of America';

i tried even by giving id of that record..but getting error as if illegal assisgnment..could any one help me out please
Sai harsha 7Sai harsha 7
Hi Mansoor S 5

First you need to insert account record and then use that account id in the opportunity. Please follow the below steps

Account acc = new Account();
acc.Name = 'Burlington Textiles Corp of America';
acc.mail = yahoo@yahoo.com;
insert acc;

then now you can reference account id in the below opportunity record.

Opportunity oppty = new Opportunity();
oppty.account = acc.id;
insert oppty;

Please mark it as a best answer.

Regards,
Harsha
Devi ChandrikaDevi Chandrika (Salesforce Developers) 
Hi Mansoor,
You have to give the field name as accountid while populating lookup value in apex class.You should give lookup recordId not name
Public opportunity op = new opportunity();
op.accountid = '0012v00002xxxxxxx';


Hope this helps you
Let me know if this helps you, kindly mark it as solved so that it may help others in future.

Thanks and Regards