[SalesForce] Custom New Button that creates record of specific type and parent record in Visualforce Controller (No URLFOR!)

Sorry for the lengthy title. But I want to make sure that I was not able to solve my problem with the standard answers to questions like this.

I have a CustomObject_c that has many record types and a Parent_c object where a user should be able to add record of this CustomObject__c. But instead of showing the regular "New" button with the subsequent record type selection page I want multiple New buttons for each Record Type.

This first part is easy as in my newRecordOfTpeX() action method I can just add the record type as part of the URL. But I couldn't find a single word on how to easily prepopulate the Parent__c relationship.

I analysed the URLs that the URLFOR method created an it uses field IDs as parameter keys. How – without using the Metadata API from APEX – should I ever be able to find out the Ids of my relationship fields?!

Best Answer

Even metadata API won't help you in finding field Ids ;)

For custom fields (like a lookup to your parent object) they're just Ids you see in the URL when you navigate in setup to the field definition. For standard fields - it's easiest to just use Firebug or similar tool that lets you inspect HTML and learn name attributes of fields on standard page layouts. (this works on custom fields too, just sounds like bit more work when the Id is sitting right there in the URL...)

There's excellent blog post by Ray Dehler to get you started. Another useful link lists all standard fields.


Now, whether you should do it... Field Id will be different when you deploy the field from sandbox to prod. It will get stable once the field got deployed to production and you refresh all sandboxes from prod (like record types or reports if you've ever noticed that). If the field is already there - you could hardcode it and the URLFOR-like solution might be really a way to go ;) It's a bit fragile though and forget about it if you'll ever plan to package your custom buttons... You could store it in some custom setting I guess?

A more sane approach would be to create a VF page & controller extension and then make several buttons that link to it. Something like /apex/newChildObjectPage?parent=001...&recordTypeName=rec1 will be more readable later in maintenance. Painful to have to recreate the new/edit page from scratch though...