Thursday 6 March 2014

How to pass values from Javascript to an Apex Controller using apex:actionFunction and apex:param components?


Through JavaScript Remoting for Apex Controllers , we come to know that parameters can be passed from JavaScript to the Apex controller's method annotated with @RemoteAction. Let's see how to pass values from Javascript to an Apex Controller using apex:actionFunction and apex:param components.



Code Snippet

JavaScript

  1.   

Visualforce Page

  1.   
  2. <apex:actionFunction name="doSelectedMaterials" action="{!handleSelectedMaterials}"  reRender="" status="statusAddRemove">  
  3.     <apex:param name="p1" value="" assignTo="{!contextMaterial}" />  
  4. </apex:actionFunction>  
  5.   
  6.   
  7. <apex:actionFunction name="doDeSelectedMaterials" action="{!handleDeselectedMaterials}" reRender="" status="statusAddRemove">  
  8.     <apex:param name="p2" value="" assignTo="{!contextMaterial}" />  
  9. </apex:actionFunction>  
  10.   
  11. <apex:inputCheckbox id="idCheckbox" value="{!subs.IsSelected}" onclick="" onchange="doCheckboxChange(this, '{!subs.parentMaterial.ContractNumber}-{!subs.parentMaterial.MaterialNumber}')" />  


Apex Controller

  1. public String contextMaterial { get; set; }  
  2. public Set setSelectedMaterials ;  
  3.   
  4. //Handle selected Materials  
  5. public void handleSelectedMaterials(){  
  6.   if(mapMaterial.containsKey(contextMaterial)){  
  7.   setSelectedMaterials.add(mapMaterial.get(contextMaterial));  
  8.   }  
  9.   
  10.   
  11. }  
  12.   
  13.   
  14. //Handle de-selected Materials  
  15. public void handleDeselectedMaterials(){  
  16.   if(mapMaterial.containsKey(contextMaterial)){  
  17.   setSelectedMaterials.remove(mapMaterial.get(contextMaterial));  
  18.   }  
  19. }  


Points to be noted

The caveat here is: You must specify a reRender attribute in the tag.
Without this, the generated function does take any parameters, but as soon as you put it in place, it does - even if you just leave it empty.


Happy Apex Implementation...!
  

No comments:

Post a Comment

Thank you for visiting. Your comments are highly appreciated.