[SalesForce] Add Custom Button to Visualforce Page

I've got a Custom Object called Opportunity__c and a Custom Button (onClick JavaScript) called Convert_to_Vacancy. Finally, I've got a Visualforce Page called Opportunity that overrides the record's View.

I'm trying to make use of the button and include it in the Opportunity Visualforce Page, but I'm not having a lot of luck doing something I thought would be simple.

I've tried:

<apex:commandButton action="{!$Action.Opportunity__c.Convert_to_Vacancy}" value="Convert to Vacancy" />

But this won't work, the response is a load of JSON my IDE can't parse.

<apex:commandButton action="{!Convert_to_Vacancy}" value="Convert to Vacancy" />

But this won't work (as expected) because of this error:

Unknown method 'Opportunity__cStandardController.Convert_to_Vacancy()

And

<apex:commandButton action="{!URLFOR($Action.Opportunity__c.Convert_to_Vacancy)}" value="Convert to Vacancy" />

Which redirects me to a Page that doesn't exist, regardless of whether I add Opportunity__c.Id as a parameter in URLFOR.

I'm lost here, how do I include an onClick JavaScript button on a Visualforce Page that overrides the standard view?

Best Answer

If you move the logic to a Visualforce Button, it is much more straightforward to reuse, thanks to the URLFOR syntax.

<apex:commandButton action="{!URLFOR($Page.MyButtonPage, null, [Id=Opportunity__c.Id])}" />

If you must stick with Javascript, it's slightly less straightforward. As far as I know, any Javascript code you place directly in the button configuration is going to be impossible for you to reuse. You need to put it somewhere you can get it! Static Resources to the rescue.

You will likely need to tweak your style to use the same Javascript in your custom button and on a Visualforce Page, but you can put the code somewhere both can use it. The structure would be something like:

Static Resource

(function (w) {
    "use strict";
    w.myButtonController = w.myButtonController || {};
    w.myButtonController.doStuff = function () {
        // logic here
    });
    Object.freeze(w.myButtonController);
}(window));

Custom Button

{!REQUIRESCRIPT('/resource/ModalButton')}
(function (w) {
    "use strict";
    w.myButtonController.doStuff();
}(window));

Visualforce Page

<apex:commandButton styleClass="myButton" value="Do Stuff!" />
...
<script>
    (function (w, D) {
        "use strict";
        D.getElementsByClassName("myButton").forEach(function (element) {
            element.addEventListener("click", w.myButtonController.doStuff);
        });
    }(window, document);
</script>
Related Topic