Setting default field values in apex for new objects

We need to set some default values in apex on a custom object before it is created. The user should ideally work with the standard object page – we don’t want to re-create the whole page in visualforce if not necessary.


Approach 1

Redirect the ‘New’ button to a custom VF page which loads the defaults and passes them on to the standard page via redirect using URL parameters.

Page (partial):

<apex:page standardcontroller="MyObj__c"
    extensions="MyObjController"
    action="!redirectDefaults">

Controller (partial):

public PageReference redirectDefaults() {
    string defName = someComplexLogic();
    PageReference retPage = new PageReference('/a0H/e?Name' + defName);
    return retPage.setRedirect(true);
}

Question: The problem here is that fields must be passed in a locale specific format : you have to know the user locale and then pass mm/dd/yyyy or dd.mm.yyyy as the case may be. How can this be done?


Approach 2

Re-create the page in visual force as an extension of a standard controller. This is more work but I assume there must be a way to initialise an instance of myObj before the page is displayed.

Question: How do I initialise myObj in my controller before the form is loaded?


Any better approaches than these are more than welcome!

Answer

For the Approach2 i would take ApexPages.StandardController:

public with sharing class YourController{

    private MyObj__c obj;

    public YourController(ApexPages.StandardController controller){
        this.obj = (MyObj__c)controller.getRecord();
    }
}

More info about StandardController Class

To Approach1.

UPDATE:

It is not a problem to pass date parameter in a current user locale. For that just use format() method of the Date class:

String s = Date.today().format(); 

and then:

'/a0H/e?DateField=' + s

The s looks for me in europe like 21.02.2013. In US it will be 02/21/2013.

From here

And for the default value of a custom field i would try to use a Default Value Formula

Attribution
Source : Link , Question Author : Marc , Answer Author : Sergej Utko

Leave a Comment