Passing method parameters with apex:actionFunction

I have this Visualforce code snippet in a page:

<apex:outputLink value="javascript:if (window.confirm('Are you sure?')) DeleteQuoteLineItem('{!LineItem.QuoteLineItem.Id}');">
    Del
</apex:outputLink>

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

The two methods I’m using for testing are:

public void DeleteQuoteLineItem(String RecordID)
{
    System.debug('method with a paramater');
    System.debug(RecordID);
}

public void DeleteQuoteLineItem()
{
    System.debug('method without a parameter');
}

Everytime I click on the link to execute the apex:actionFunction, it’s calling the DeleteQuoteLineItem() method without any parameter. I looked online and it seems like I need to create a class attribute and use assignTo= in my apex:param to populate it accordingly.

Is it possible to prevent this behavior and use standard method parameters, so I don’t have to create class attributes? I want to work on a clean and optimized codebase, preventing unnecessary variable scope (so no class attribute when it’s not required) and improve code re-usability by staying context agnostic.

Thanks

Answer

You can access the param that was passed directly inside you controller using the ApexPages class or the system class.

VF

<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

public void DeleteQuoteLineItem(){

    //either of the next 2 lines will work, 
    string passedParam1 = Apexpages.currentPage().getParameters().get('myParam');
    string passedParam2 = system.CurrentPageReference().getParameters().get('myParam');
    system.debug(passedParam1);
    system.debug(passedParam2);
}

Im just curious as to why you are opposed to using class properties to assign the params to. Both ways will work, just curious if you have a unique use case or just curious of other ways of accomplishing it. Hope this helps

Attribution
Source : Link , Question Author : jpmonette , Answer Author : Chris Duncombe

Leave a Comment