3

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?

0

1 Answer 1

4

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>
1
  • 1
    Damn, I was hoping I was missing something simple here with "calling" the button to the page. Luckilly the button just calls a helper class anyway, so this shouldn't be too problematic. Thanks for clearing this up Adrian.
    – Dan Jones
    Dec 6, 2016 at 6:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .