2

I'm trying to adapt logic from this old post by having a javascript function call an apex:actionFunction instead of apex:outputLink. Here's my VF page:

<apex:page controller="testParam">
<apex:form >
<script type="text/javascript">
    function func1(val) {
      DeleteQuoteLineItem('TEST VALUE from func1');
      alert("func1: "+val);
    }
</script>

    <apex:pageBlock >
        <apex:pageBlockButtons >
            <apex:commandButton value="Query" onclick="func1('a')" rerender="content"/>
        </apex:pageBlockButtons>
    </apex:pageBlock>

    <apex:outputLink value="javascript:if (window.confirm('Are you sure?')) DeleteQuoteLineItem('TEST VALUE');">
    Del
    </apex:outputLink>

    <apex:actionFunction action="{!DeleteQuoteLineItem}" name="DeleteQuoteLineItem" rerender="content">
        <apex:param name="myParam" value=""/>
    </apex:actionFunction>

</apex:form>
</apex:page>

The controller is simply:

public class testParam {

    public PageReference DeleteQuoteLineItem() {
    string passedParam1 = Apexpages.currentPage().getParameters().get('myParam');
        system.debug('Delete Quote Line Item with '+passedParam1);
        return null;
    }

}

In any case, clicking apex:outputLink calls the controller method successfully, but clicking the apex:commandButton does not. I do see my alert fire but the controller method does not seem to be called at all. Is what I'm trying to do is illegal?

  • Scott, I've fixed your code for you. The `` is used for inline code. Prefix each line of block code with four spaces to get it to format as a block, or if you can use Ctrl/Cmd+K after selecting the text, it will automatically indent your code for you. – sfdcfox Jan 2 '15 at 21:12
3

You're not cancelling the button's default action, which causes the default form processing to occur (which ultimately re-renders the page). I wouldn't be surprised if this causes some Bad Things to happen. You'll want to prevent the default form processing by returning false:

onclick="func1('a');return false;"

The link doesn't have a problem, because you're setting the rendered link's href attribute to a JavaScript function, so there's no other library code being called/page being unloaded/etc.

  • That worked! Is this because the page refresh would cancel the call to the controller's method? Re-reading the docs says if an action is not specified the page simply refreshes. – Scott Jan 2 '15 at 21:50
  • That's right. Browsers tend to forcefully terminate all open connections when a page unloads (that's why we have a "before unload" function), so the reload cancels anything that would have been called. – sfdcfox Jan 2 '15 at 21:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.