we have created an APEX class that creates a contract object from an opportunity object. We need to create a custom button on contract object to copy some field values from the related opportunity object to the new contract object and I do not really how to do it. This step is not mandatory (for this reason I have not include that in the apex class), it is just an option for the users and has to be done always once the contract object has been already created. I have in a custom contract field the associated opportunity id. Thanks in advance.
Running apex from a custom button is a fairly common requirement. The trick is if you need it to be protected against CSRF or included as part of a managed package.
At the simplest level you can create a custom button link on Contract to custom Visualforce page that takes the Contract ID as a query string parameter. The custom Visualforce page will then use the action attribute of the apex:page to fire a method in the controller. The method returns a PageReference that redirects back to the Contract when complete. See an example at: Custom Button or Link to a Visualforce page with a custom controller
Making it work in a CSRF safe way with managed packages is a bit more tricky. Last I checked you need an intermediate page or a custom Contract Detail page. See CSRF safe Custom button linked to Apex method
Alternatively, you could expose your apex method as a webservice method and then invoke it using sforce.apex.execute via a javascript button. This isn't ideal if you don't want others to be able to call the webservice.
You should just start by looking at Ray Dehler's URL Hacking post . This was all I needed to read up on URL hacking and custom buttons. If all you are doing is creating a contract from the opportunity and either copying values from it or hardcoding then this should be enough reading..
-
URL hacking is unsupported, won't work via Salesforce1, and is generally a bad idea, especially if you're already using apex in your org! – ca_peterson Feb 13 '14 at 19:53
-
Yeah of course it's unsupported,but I've used pretty successfully over the years in a pretty large org and don't remember any huge problems regarding the use thereof. Salesforce do provide Chatter Actions that are able to do mostly the same thing, otherwise it's just a matter of writing an apex class and having a button that uses OnClick Javascript and calling the class. I use a mixture of both. Whatever works. – akarnid Feb 13 '14 at 20:04