+ Start a Discussion
MicheTMicheT 

Building a visualforce form

Trying to build a form but need help with apex controller

I am trying to build a form that combines both account and contact fields. The form is for us to be able to track whenever a customer stops doing business with us. Sometimes it is the entire account and sometimes it is just a specific contact within that account.

When I try to build out the visualforce page it says that I need to have an apex controller. If there is a standard one that combines both accounts and contacts, what is it? If not, how do I build a custom apex controller?

I need to show the following fields on the form:
Account Fields:
Account Name
Corp ID
Territory
Reason Lost
Reason Lost to Competitor

Contact Fields
Contact Name
Title

Any suggestions on how to build this as a form would be really helpful. I have not worked with visualforce too much in the past, hence the confusion. Thank you in advance!!
 
Andrew EchevarriaAndrew Echevarria
Here is a great example on how you can build a custom controller, it will walk you through step by step and I think the exercise is relavent to your needs too!

https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_controller_custom.htm
MicheTMicheT
Hi Andrew - Thank you. This one shows how to add account fields but I am not sure how to add account and contact fields since I need to be able to pull information from both objects.
Andrew EchevarriaAndrew Echevarria
Just add add the variable + function below to the code for contact and then the query + "update contact" to the existing functions. Add another url reference of of course for the Contact Id, then you can test via salesforce.com/apex/pageName?id=[AccountId]&ContactId=[ContactId] and it will load the respective object records.

Is this your first apex controller? It may be easier for you to first write and test for one object, then copying the methodology for the second
 
private final Contact contact;

public Account getContact() {
        return contact;
    }

 
Andrew EchevarriaAndrew Echevarria
This should suit your needs. Test with salesforce.com/pageName?id=[AccountId]&Contactid=[ContactId]
 
public class MyController {

    private final Account account;
    private final Contact contact;

    public MyController() {
        account = [SELECT Id, Name, Site FROM Account 
                   WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
	contact = [Select Id, Name from Contact where Id = :ApexPages.currentPage().getParameters().get('Contactid')];
    }

    public Account getAccount() {
        return account;
    }
    public Account getContact() {
        return contact;
    }

    public PageReference save() {
        update account;
	update contact;
        return null;
    }
}