Thursday, 16 October 2014

Apex Map into JSON for use in Javascript / jQuery

Introduction

Ever wondered how to use your apex map into javascript / jQuery for your VisualForce development?
Please find below a way to do it.

Note: jQuery is required in this tutorial.

Apex Class (Visualforce Controller)

Suppose we populate a map with key Id and value as a list of Ids, say mapParentIdListChildrenId in our controller.
We then declare a getter to access this map as JSON in our VF page.
 public Map <Id, List <Id>> mapParentIdListChildrenId{get;set;}
 public String mapParentChildrenJSON {get{return JSON.serialize(mapParentIdListChildrenId);}}
Visualforce Page

The JSON String mapParentChildrenJSON is converted into javascript object as shown below:
 <script> 
  $(function() {
     var $mapParentChildren = jQuery.parseJSON('{!JSENCODE(mapParentChildrenJSON)}');
     console.log($mapParentChildren);
     // var value = $mapParentChildren[key]; // can be used to access values of the map
  }
 </script>
Use the Console of your browser to inspect the elements in your map ;)

Cheers & Happy Coding !!
Gulshan.

No comments:

Post a Comment