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
A chauhanA chauhan 

Apex class code for storing Account name (lookup) value in opportunity object with custom controller

I have custom controller Request_page .i want to create account name(lookup) field in my visualforce page and wants that account name value to be stored in Opportunity object Account name ! what should be the visualforce page code and apex code ?
SandhyaSandhya (Salesforce Developers) 
Hi Chauhan,

Please refer below sample code.
<apex:page controller="OpportunitySave">
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection >
    <apex:inputField value="{!opp.Name}"/>
    <apex:inputField value="{!opp.StageName}"/>
    <apex:inputField value="{!opp.CloseDate}"/>
        <apex:inputField value="{!opp.Accountid}"/>
    <apex:commandButton value="Submit" action="{!insertOpp}"/>

public class OpportunitySave{
    public Opportunity opp{get;set;}
    public OpportunitySave(){
        opp = new Opportunity();
    public void insertOpp(){
        insert opp;

Hope this helps you!

Please accept my solution as Best Answer if my reply was helpful. It will make it available for other as the proper solution. If you felt I went above and beyond, you can give me kudos.
Thanks and Regards

SandhyaSandhya (Salesforce Developers) 
Hi ,

It's saving for me I have tested it now.are you getting any error? Try put system.debug in the controller System.debug('oppp' +opp); before insert and see what values you are getting debug logs in the developer console.

User-added image

Thanks and Regards
SandhyaSandhya (Salesforce Developers) 
Are you checking here setup -- opportunities -- rtterter  ?
SandhyaSandhya (Salesforce Developers) 
Hi Chauhan,

ok its similar way you used for other fields like Type, StageName, just use 
Opp.Accountid= account; the Only thing is for lookup we use Accountid as the reference name.

Thanks and Regards