[SalesForce] CommandLink or CommandButton as New Button to create a new record of a specific record type

Instead of having a user to click "New" and then select the record type before he sees my custom New page I want 3 Buttons that let him create a record of on of three potential record types.

I know there is a URLFOR syntax for that but couldn't get this to run because I can't hardcode the recordtypeIds as this will be differnt on the target org.

Is there a way to use this URLFOR method with variables for the record type or how else can I solve this?

Maybe with a custom controller action would do the job?!

Best Answer

You can use the key prefix in conjunction with the RecordType parameter in a custom controller or extension. The basic idea is below. The developer name should be stable and not change between orgs. Also, once in production the ID doesn't change in sandboxes refreshed from production, so if you are already working with a record type that is in production you could use the ID.

You can adapt this code to be more specific or to not be an extension. The main thing is the format of the URL and the idea that the RecordType ID is retrieved in a relatively stable way.

public class BypassRecTypeController {
    private sObject rec;
    private String recTypeDevName;

    public BypassRecTypeController(ApexPages.StandardController controller) {
        rec = controller.getRecord();

        // might get this some other way...
        recTypeDevName = ApexPages.currentPage().getParameters().get('recTypeDevName');
    }

    public PageReference bypass() {
        // Get the key prefix to use as part of the url
        // Alternatively, if you know the SObject you could have something like
        // Account.SObjectType.getDescribe() hard coded.
        Schema.DescribeSObjectResult dsr = rec.getSObjectType().getDescribe();
        String keyPrefix = dsr.getKeyPrefix();

        // Get the record type to add on to the query string
        Id recTypeId = [Select Id From RecordType Where DeveloperName = :recTypeDevName].Id;

        PageReference pageRef = new PageReference('/' + keyPrefix + '/e?RecordType=' + recTypeId);

        return pageRef;
    }

}