[SalesForce] How to use the same Visualforce page to override view, new, and edit buttons on custom object

I have a custom Visualforce page for a custom object. I have overriden the new, edit, and view buttons to point to this page. I would like to dynamically change the look of the page based on what mode the user is in.

For example, show an <apex:inputField /> when they are editing, but an <apex:outputField /> when viewing:

<apex:outputField value="{!MyCustomObject__c.Field1}" rendered="{!pageMode == 'view'}" />
<apex:inputField value="{!MyCustomObject__c.Field1}" rendered="{!pageMode == 'edit'}" />

I would also use this property to set the mode attribute of my <apex:pageBlock />

Is there a good way to do this using a button override? I do not want to create custom buttons and use URL parameters if I can avoid it.

Best Answer

This will lead to a lot of conditionally rendered tags. You might consider having separate page for "view" and separate for "new/edit" but use same controller extension if you really want.

But if you're determined... You can look at the URL that was used to navigate to your page and combine it with presence of Id in the standard controller.

I've called my page override and used Opportunity as the test object.

New: /apex/override?retURL=%2F006%2Fo&save_new=1&sfdc.override=1
View: /apex/override?id=0067000000AH3ME&sfdc.override=1
Edit: /apex/override?id=0067000000AH3ME&retURL=%2F006%3Ffcf%3D00B70000005pFQv%26rolodexIndex%3D-1%26page%3D1&sfdc.override=1

Something like this should work, at least until SF decides to rename/remove the retUrl param (unlikely I'd say... Especially than on viewing there's rarely something to cancel or "on success return to... where?").

public MyExtension(ApexPages.StandardController ctrl){
    Id i = ctrl.getId();
    Map<String,String> parameters = ApexPages.currentPage().parameters();
    if(i == null){
        System.debug('new');
    } else if(parameters.contains('retUrl')){
        System.debug('edit');
    } else {
        System.debug('view');
    }
}