[SalesForce] retURL from the saveURL isn’t working after passing through recordtypeselect.jsp

This button code overrides the new button on a custom object. It sends the user to the record type selector, and then passes in a couple of params. When the user gets to the new record edit page, and THEN clicks cancel, he goes back to https://cs16.salesforce.com/home/home.jsp not the accountId page as I want. Can someone help me with the syntax?

       Schema.DescribeSObjectResult dsr = customObject__c.SObjectType.getDescribe();
        Account a = [select id, name from Account where id = :this.AcctId];

        url = '/setup/ui/recordtypeselect.jsp?';
        url += 'ent=' + '01I30000001ITcu&';
        url += 'retURL=/' + a.id ;
        url += '&nooverride=1';

        url += '&save_new_url=/' + dsr.getKeyPrefix() + '/e?';
        url += 'CF00N3000000689TM=' + EncodingUtil.urlEncode(a.name, 'UTF-8') ; 
        url += '&CF00N3000000689TM_lkid=' + a.id;           
        url += '&retURL=/'+ a.id; 

Best Answer

The issue here is that the save_new_url value needs to be encoded so that those parameters don't replace the parameters with the same names in the recordtypeselect.jsp URL. Note that I used the encoded %2F in place of the / in the saveNewUrl string.

I typically use a PageReference to do this as it automatically handles the URL Encoding and is a lot less fragile and error-prone than building a string by hand.

PageReference pageRef = new PageReference('/setup/ui/recordtypeselect.jsp');
pageRef.getParameters().put('ent', '01I30000001ITcu');
pageRef.getParameters().put('retURL', '/' + a.Id);
pageRef.getParameters().put('nooverride', '1');

// using string.format for parameter substitution pattern
String saveNewURL = String.format('/{0}/e?CF00N3000000689TM={1}&CF00N3000000689TM_lkid={2}&retURL=%2F{3}', new List<String> { dsr.getKeyPrefix(), EncodingUtil.urlEncode(a.name, 'UTF-8'), a.Id, a.Id });
pageRef.getParameters().put('save_new_url', saveNewURL);

// output the generated, properly-encoded URL
system.debug(pageRef.getURL());

Example debug output, with the second retURL value now double-encoded:

|DEBUG|/setup/ui/recordtypeselect.jsp?ent=01I30000001ITcu&nooverride=1&retURL=%2Fa.Id&save_new_url=%2F001%2Fe%3FCF00N3000000689TM%3Da.name%26CF00N3000000689TM_lkid%3Dabc123%26retURL%3D%252Fabc123
Related Topic