How to return a PageReference to create a sObject in salesforce

salesforce

Solution

I had the same problem when trying to add a Save and New button. It seems odd that the StandardController doesn't have a new() method that returns a PageReference.

If your Apex class is going to be deployed to another Salesforce org (E.g. added to an outbound change set, put in a managed or unmanaged package, or deployed using Eclipse) I'd avoid hard coding the custom objects key prefix as this could change between orgs. Instead, use the DescribeSObjectResult to get the KeyPrefix.

public PageReference customObjectPageReference() {
    Schema.DescribeSObjectResult R = YourCustomObject__c.SObjectType.getDescribe();
    // Add /o to end of URL to view recent
    return new PageReference('/' + R.getKeyPrefix() + '/e');
}

Problem

I know how to return a PageReference to edit and view a sObject: ``` PageReference ref = new ApexPages.StandardController(bnk).edit(); ``` But the StandardController class hasn't any method like create. How can I return the page to create the sObject. I alse know the methed like: ``` PageReference ref = new PageReference('/a00/e'); ``` but the sObject has many lookup fields.This method can't take out the reference lookup fields.It only can create a standalone sObject. So how to return the create page and also take out the reference lookup fields?

Original source