Friday, August 24, 2018

How to pass parameters to a JS function from VF page and then call apex method.??

Suppose requirement is that you want to send the id of a record to the apex method and your records are displaying on visualforce page using apex repeat. So this example will solve your problem.

visualforce page code


<apex:repeat value="{!contactList}" var="contact">
                    <tr>
                        <td>{!contact.Account.Name}</td>
                        <td onclick="myFunc('{!contact.Id}'); return false;">{!contact.FirstName}</td>
                        <td>{!contact.LastName}</td>
                        <td>{!contact.Phone}</td>
                    </tr>                                 
</apex:repeat>

so on the click of firstname you will call a js function that will call your action function and then you can call your apex method and pass your parameters


<script>
function myFunc(conId){           
         callActionFunction(conId);         
 }
         
</script>

your action function code put this code to your visualforce page


<apex:form id="fd">
            <apex:actionFunction action="{!callApexMethod}" name="callActionFunction"  rerender="">
            <apex:param id="myParam" name="contactid" value="" />
            </apex:actionFunction>
           
  </apex:form>

Apex Class


public void callApexMethod(){
         string passedParam1 = Apexpages.currentPage().getParameters().get('contactid');
      // write your logic here what you wanna perfom with id you just received from the contact recordyou click
}

Hopefully you get some information from this blog. If you have any problem you can comment down so that i can solve your problem. Thanks!