4

I'm trying to access a the apex Map named "resultsMap" with javascript, I would like to get contact last name using contact id.

public class AccessMapJS {
    public Map<ID, Contact> resultsMap{get;set;} 
    public String JsonMap{get;set;} 

    public AccessMapJS(){
        resultsMap = new Map<ID, Contact>([SELECT Id, LastName FROM Contact limit 3]);
        JsonMap=JSON.serialize(resultsMap); 
    }
}

VF page:

<apex:page controller="AccessMapJS" >
<script>
// Access here resultsMap: get contact last name using contact id


</script>
  {!resultsMap}
</apex:page>

Do you know hoe to accomplish that ? Thanks in advantage for any advice.

3 Answers 3

3

Your controller is fine.

You can get it in via javascript if thats your preference:

var contactMap = JSON.parse('{!JsonMap}');
var lastname = contactMap['003....'].LastName;
0

Your page is fine, in that it will show the data being piped into it, but your controller needs a bit of work.

Controller:

public class ContactMapController {

private List<Contact> getContacts()
{
    return [SELECT Id, LastName FROM Contact limit 3];
}

private  Map<ID, String>  getLastNamesMap (List<Contact> contacts)
{
    Map <ID, String> result = new Map <Id, String>();
    for (Contact contact: contacts)
    {
        result.put (contact.Id, contact.LastName);
    }
    return result;
}

public  Map<ID, String> getAccessMap()
{
    List<Contact> contacts = getContacts();
    Map<ID, String> result = getLastNamesMap(contacts);
    return result;
}

}

I renamed the controller, separated out the required logic into separate methods and changed it to just return the information you wanted.

Here's the page:

<apex:page controller="ContactMapController" >
<h1>Contacts</h1>
<p>
  {!accessMap}
</p>
</apex:page>
1
  • Thanks for the inputs, but i asked something different. I wanted to access the map in Javascript not VF
    – Enry
    Mar 21, 2015 at 17:02
0
*You can try the below code and i hope it works.
<script>
// Get the String notation for the Apex Map Created. Currently contains attributes, Id and Name
var jsMap = '{!JsonMap}';
// Use the parse Method for getting Object Array from the map. 
var jsonObjArr = JSON.parse(jsMap);
// Create a Javascript Object
var map = new Object();
// Iterate throught the Array and Push into map Object
for(var count=0;count<jsonObjArr.length;count++)
{
   // JSON Object 
   var JSONObj = jsonObjArr[count];
   // Map key : Contact Id
   var ConId = jsonObjArr[count].Id;
   // Map Contact Id to JSON Object. Then you can use this object to get values  from Map. Storing Object in case you need more information than just Last Name. 
   map[ConId] = JSONObj;
}
// Get the Last name using get Notation for the first Id. In case you know the Id jsut pass it.
alert(map[jsonObjArr[0].Id].LastName);
</script>*

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .