Wednesday, April 11, 2012

Setting Default Values to Record - Using Visualforce to Override New Button

The goal is to set some default values to a record, there are times that you can not set the proper default value to fields when using the 'Set Default Value' option on a field. A lookup value can be a prime example and that is why I had to research this.

You need 2 things, an apex class that puts together the URL for the page, and a Visualforce page that basically outputs the URL that is generated in the class.

Below are my two items, the Visualforce page code as well as the class that it invokes.

Visualforce Page Code:

<apex:page standardController="Account_Child__c" extensions="DefaultAccountController" action="{!putDefault}">

</apex:page>

APEX Class Code:

 public class DefaultAccountController {
public DefaultAccountController(ApexPages.StandardController controller) {
    }
 
    public PageReference putDefault() {  
String tester = getAccount().Name;
//creating a page reference
PageReference pageRef;      
//Variables to hold the URL parameters  
String retURL =  ApexPages.currentPage().getParameters().get('retURL');
String retIDName =     ApexPages.currentPage().getParameters().get('CF00NC00000053NfO');      
String retAcctID =     ApexPages.currentPage().getParameters().get('CF00NC00000053NfO_lkid');
//Variables from the parent account
List <Account> acct = [select id, name, phone,industry from Account where id =:retAcctID];
string acctNum = acct[0].phone;
string acctInd = acct[0].industry;
//The URL that will be used in the new VF page
pageRef = new PageReference('/a0A/e?CF00NC00000053NfO='+retIDName+'&CF00NC00000053NfO_lkid='+retAcctID+'&Name='+acctNum+'&00NC00000053NfY='+acctInd+'&retUrl='+retURL);  
//adding nooverride to prevent infinite loop  
pageRef.getParameters().put('nooverride', '1');          
pageRef.setRedirect(true);          
//Item that is returned when this class is invoked is the PageRef URL
return pageRef;
}

The highlighted items below should appear on a single line of code.

This is a link to the developer.force.com post that was helpful in creating this.

http://boards.developerforce.com/t5/General-Development/How-to-set-standard-field-to-a-Default-value/m-p/333595/highlight/true#M60358

No comments:

Post a Comment