[SalesForce] Commandbutton Link to Visualforce Page Giving “SObject row was retrieved via SOQL without querying the requested field”

I have a strange Visualforce problem: a commandbutton throws a "SObject row was retrieved via SOQL without querying the requested field", but the same URL works as a straight-up link.

Markup is

<apex:commandbutton value="TMC Member Checklist" action="/apex/MemberFileChecklist?id={!Contact.id}" />

vs.

<a href="/apex/MemberFileChecklist?id={!Contact.id}">Member File Checklist</a>

Does anyone know why the link would work and the command button throw an error? Both are links to the same Visualforce page.

Best Answer

The commandButton's attribute action is not to use as forwarding element. Here some info from the docs:

The action method invoked by the AJAX request to the server. Use merge-field syntax to reference the method. For example, action="{!save}" references the save method in the controller.

Read the full doc here.

If you want to redirect the user to another page just create a PageReference apex method for that and reference it in the command button:

public PageReference redirectUser(){
    PageReference ref = new PageReference('/apex/MemberFileChecklist?id=' + contact.id);
    return ref;
}

<apex:commandbutton value="TMC Member Checklist" action="{!redirectUser}"/>

More info about PageReference.

Alternatively, you can use onclick attribute and redirect with some javascript (if you don't want to create extra apex method). In this case you dont't need the action anymore:

<apex:commandbutton value="TMC Member Checklist" 
                    onclick="window.location='/apex/MemberFileChecklist?id={!Contact.id}'; return false;"/>