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
Ajay Kumar 583Ajay Kumar 583 

To add Visual Force Page code

Hi , i have created a Button on Account object and Now i need to add the visualforce page code Which will create a Contact when the user clicks the button. How to do it
 
Raju yadavRaju yadav
Hi Ajay,
Please create a vf page and its controller .
then add vf page in the button as given ScreenshotUser-added image


Thanks,

 
Ajay Kumar 583Ajay Kumar 583
Hi Raju,

I need vf page and its controller Code to create contact on Account object. 
Thanks
Khan AnasKhan Anas (Salesforce Developers) 
Hi Ajay,

Greetings to you!

Below is the sample code which I have tested in my org and it is working fine. Kindly modify the code as per your requirement.

Visualforce:
<apex:page StandardController="Account" extensions="DetailPageButtonC">
    <apex:form id="form">
        <apex:pageMessages />
        <apex:pageBlock >
            
            <apex:pageBlockSection title="Create Contact" columns="1">
                <apex:outputField value="{!acc.Name}"/>
                <apex:inputField value="{!con.FirstName}"/> 
                <apex:inputField value="{!con.LastName}"/>
                <apex:inputField value="{!con.Phone}"/>                        
                <apex:inputField value="{!con.Email}"/>   
                <apex:commandButton value="Save" action="{!saveCon}" />
            </apex:pageBlockSection>
            
        </apex:pageBlock>
    </apex:form>
</apex:page>

Controller:
public class DetailPageButtonC {
    
    public Contact con {get;set;}
    public Account acc {get;set;}
    
    public DetailPageButtonC(ApexPages.StandardController controller) {
        con = new Contact(); 
        String str = ApexPages.CurrentPage().getparameters().get('id');  
        acc = [SELECT Id, Name FROM Account WHERE Id=:str];
    }  
    
    public void saveCon(){
        con.AccountId = acc.Id;
        INSERT con;  
    }
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Ajay Kumar 583Ajay Kumar 583
Hi Khan ,

I am getting below error:
Insert failed. First exception on row 0 with id 0032v00002pPocnAAC; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]


And i dont want the page to render.  Button should automatically create a custom contact without giving the page.

Thanks,
Ajay