[SalesForce] Visualforce Button Redirect with URL reference to related Account

I am working on a small wizard for adding Contacts of a certain type. The first page redirect is saving and redirecting with the ContactID referenced in the URL like it is supposed to, but the second redirect I can't quite figure out. I need it to put the related AccountID in the URL

I'm hoping there is something small that I'm just overlooking, but could really use some help figuring out what I'm doing wrong. The problem is in the public PageReference goToContactMgm section. Here is my controller code:

global class NewCustomerContactController {

     private ApexPages.StandardController controller;

     public NewCustomerContactController(ApexPages.StandardController controller) {
         this.controller = controller;

     }

     public PageReference saveAndNext() {
         if(controller.save() != null) {
             PageReference redirectPage = Page.NewContactAssociateToBilling;
             redirectPage.setRedirect(true);
             redirectPage.getParameters().put('id',controller.getId());
             return redirectPage;
         } return null;
     }

     public PageReference goToContactMgmt() {
             PageReference redirectPage = Page.ContactRole;
             redirectPage.setRedirect(true);
             //The controller.getID below returns the Contact ID, and I have been playing with it to see if I can find a way to get it to return the Account ID instead
             redirectPage.getParameters().put('id',controller.getId());
             return redirectPage;
     }
}

I also tried, which tells me that the Contact variable doesn't exist, and doesn't seem to allow me to directly reference a field in my page.

 public PageReference goToContactMgmt() {
     PageReference pageRef = new PageReference('/apex/ContactRole?id=' + Contact.AccountId);
     return pageRef.setRedirect(true);
 }

One thought I had was to create the variable to the Contact and create a Query to reference the field for the AccountID, but it seems like there should be an easier way since it's a field referenced right in the Contact.

Best Answer

After querying the contact you should be able to use your second attempt

public PageReference goToContactMgmt() {
    Contact c = [ select AccountId from Contact where Id = :controller.getId() ];
    PageReference pageRef = new PageReference('/apex/ContactRole?id=' + c.AccountId);
    return pageRef.setRedirect(true);
}
Related Topic