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
Manish Anand 10Manish Anand 10 

How to auto Populate an account name, while creating a new contact in the VF page?

Hi,

My requirement is to create a contact , by clicking a button on the account detail page. Button click will open a new vf page with contact fields onto it.Account name field on new vf page must be auto popuated, where as rest of the contact fields can be typed in.
How do I achieve this?
 
Shazib MahmoodShazib Mahmood
You will need:

1. A button on account that calls on an apex page + gives account ID in URL. Button will be made on contact object. I use list button as javascript. e.g window.location = 'apex/VFpage?AccountId={!AccountId}'
2. VF that call on a controller.
3. Controll will grab the value from URL. It will perform any logic and then redirect to new page reference and in URL provide field ID = value that you were passed on from first 2 steps. You will have to hardcode the account field IDs in custom settings and then reference them.
Manish Anand 10Manish Anand 10
Hi Shazib,

Could you please write the sample code for this?
Mahesh DMahesh D
Hi Manish,

You can chieve the same functionality using the Salesforce Standard button on the related list as below:

User-added image

User-added image

If you want have a button on the Account detailed page but not on the Related list then

==> Create a VF page with the below code:
 
<apex:page standardController="Account" extensions="CreateContactFromAccountController">
    <apex:form>
        <apex:pageBlock>
            <apex:pageBlockSection>
                <apex:inputField value="{!con.FirstName}"/>
                <apex:inputField value="{!con.LastName}"/>
                <apex:inputField value="{!con.AccountId}"/>
            </apex:pageBlockSection>
            <apex:pageBlockButtons>
                <apex:commandButton value=" Save Contact" action="{!saveContact}"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>
 
public class CreateContactFromAccountController {
    public Contact con {get; set;}
    public CreateContactFromAccountController(ApexPages.StandardController controller) {
        Account acc = (Account) controller.getRecord();
        con = new Contact();
        con.AccountId = acc.Id;
    }
    
    public PageReference saveContact() {
        insert con;
        return new PageReference('/'+con.Id);
    }
}

==> Create a button on Account object:

User-added image

Please do let me know if it helps you.

Regards,
Mahesh
Manish Anand 10Manish Anand 10
Hi Mahesh,

I requirement is different.
1)Click on Account tab, and open any account.
2)There should be a  button/link on account detail page to open a new vf page.(E.g Link should be named as- 'Add new Contact')
3)Clicking on 'Add new Contact', should open a new vf page.
4)New VF page, opened in step 4 should have:- i)Account name prepopulated from step 1 (the account name, which is opened in step 1)
  ii)First Name iii)Last Name
 
Note-In step 4, above, I don't want to select an account from lookup, rather it should have account name, which is already selected in step 1, above.

I am unable to accomplish 4) i)-Account name is not prepopulated.
So could you please tell me, how to get this done?

Regards,
Manish.
 
Mahesh DMahesh D
Hi Manish,

If you see my VF page and Controller which I posted above will perform exactly what you are asking.

Please review it and let me know your thought on it.

Regards,
Mahesh
Manish Anand 10Manish Anand 10
Hi Mahesh,

Thanks for your quick response. 
I see out of above 4 steps mentioned by me. I see 1st and 4th you have accomplished.
But also you see in steps 2 and 3. An account detail page should have a button/link. Clicking on which should open a new vf page, where I should fill contact fields and account name must already be prepopulated on that new vf page.
In your above code, I see, it asks for contact's first name and last name in the account detail page itself. Rather it should have only a button/link, clicking on which should redirect me to new vf page.
I hope, I am clear this time.

Regards,
Manish 
Mahesh DMahesh D
Hi Manish,

Please let me know what is the issue in performing the Step 2 and 3.

Regards,
Mahesh
Manish Anand 10Manish Anand 10
Hi Mahesh,

Let me explain step wise.
1)I have created a VF-testScenario5 with controller extension as-ControllerEx1 and StandardController-Account.
  This page has a commandlink-Add Contacts Or Opportunity, which is displayed on an account detail page.Clicking on this link, redirects to another VF page.(which I will mention in step 2). 
Below is the VF and Apex code of extension for this step 1.

<apex:page standardController="Account" sidebar="false" showHeader="false" extensions="ControllerEx1">
<apex:detail relatedList="false"/>
<apex:form >
<apex:commandLink action="{!Add_Con_Or_Opp}" value="Add Contacts Or Opportunity"/>
</apex:form>
</apex:page>

2)Clicking on the link-Add Contacts Or Opportunity on account detail page, redirects to another VF Page-ContactsOrOpportunity.
   which has a custom controller-MyController2.
   Below is the VF page and apex code for MyController2.
   
global without sharing class MyController2
{
   public Account acnt{get;set;}
   public Account a{get;set;}
   Contact con=new contact();
   public Contact con1{get;set;}
   public Opportunity opp{get;set;}
   Opportunity op=new Opportunity();
   public Account getAccount() {
        Account acc = new Account();
        acc.Name = 'Test Account';
        //insert acc;
        
        ApexPages.StandardController sc = new ApexPages.StandardController(acc);
        ControllerEx1 c = new ControllerEx1(sc);
        acnt = c.returnAccount();
        return acnt;
    }
        
      
   Public Pagereference InsertNewContact()
   { 
     a=getAccount();
     con1=new contact();
     con1.AccountID=a.ID;
     insert con;
     return new PageReference('/'+con.Id);
    }
    public contact getCon()
    {
      return con;
    }
     Public Pagereference InsertNewOpportunity()
     {
       a=getAccount();
       opp=new Opportunity();
       opp.AccountID=a.ID;
       insert op;
       return new PageReference('/'+op.Id);
     }
     public opportunity getop()
     {
        return opp;
     }
    }
Below is VF page-
<apex:page controller="MyController2">
<apex:tabpanel switchType="Ajax">
<apex:tab label="Add Contact" labelWidth="300">
<apex:form >
<apex:pageBlock >

<apex:commandButton Value="Add Contact" action="{!InsertNewContact}"/>
<apex:pageBlockSection >
<apex:inputField label="First Name" value="{!con.FirstName}"/>
<apex:inputField label="Last Name" value="{!con.LastName}"/>
</apex:pageBlockSection>

</apex:pageBlock>
</apex:form>
</apex:tab>
<apex:tab label="Add Opportunity" labelWidth="300">
<apex:form >
<apex:pageBlock >
<apex:commandButton Value="Add Opportunity" action="{!InsertNewOpportunity}"/>
<apex:pageBlockSection >
<apex:inputField label="Opportunity Name" value="{!op.Name}"/>
<apex:inputField label="Opportunity Stage" value="{!op.StageName}"/>
<apex:inputField label="Opportunity Date" value="{!op.CloseDate}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:tab>
</apex:tabPanel>
</apex:page>
There is no compile error.
1)When I  enter first name and last name on contact's page and click on Add Contact. It saves the contact and takes me to newly added contact page. However, the newly added contact is not associated with the account name selected in Step 1. But, I want newly created contact to be associated with the account selected in step 1.

2)When I click on 'Add Opportunity' tab and fill all the required details in the text box (Opp name, Stage, Opp date etc) and click on button Add opportunity.It throws a Run time exception as below-
System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Opportunity Name, Stage, Close Date]: [Opportunity Name, Stage, Close Date]
Error is in expression '{!InsertNewOpportunity}' in component <apex:commandButton> in page contactsoropportunity: Class.MyController2.InsertNewOpportunity:


In this case aswell, I want newly added opportunity to be associated with the Account, selected in step 1.

Hope, this clears.What I am looking for.I think, I am missing some concept like-how to pass account name from one VF page to another, though not sure.

Regards,
Manish.






 
Manish Anand 10Manish Anand 10
Mahesh,
I missed to attach controllerEX1 apex class for step 1. I am attaching it below.
 
public with sharing class ControllerEx1
{
   public final Account acct;
   public ControllerEx1(Apexpages.StandardController stdcon) {
   this.acct=(Account)stdcon.getRecord();
   }
   public Account returnAccount()
   { 
     return acct;
   }
     
     public PageReference Add_Con_Or_Opp()
     {
       PageReference pr = new PageReference ('/apex/ContactsOrOpportunity?AccountId={!AccountId}');
       pr.setRedirect(true);
       return pr;
     }
   }

 
Manish Anand 10Manish Anand 10
Hi Mahesh,

Did you get a chance to look into this?

Regards,
Manish.