4

Can you output a value from a map in a custom extension without or it being in a table? Tried the below and did not work.

example extension:

public without sharing class Example {
public List<Custom_Object__c> records {get; set;}
public Map<String,Custom_Object__c> map {get; set;}
public String recId {get; set;}
public Example(ApexPages.StandardController stdController){
    recId=ApexPages.CurrentPage().getparameters().get('id');
    records =
    [select Name, field1__c,field2__c,field3__c from Custom_Object__c where Id=:recId ];
    Map<String, Custom_Object__c> map = new Map<String, Custom_Object__c>();

    String key;
    for(Custom_Object__c record :records) {

        if(record.field3__c.contains('foo')) {
            key = 'foo_'+Name;
        }else{
            key = 'bar_'+Name;
        }
        if(record!=null) {
            map.put(key, record);
        }

    }

}
}

display values like below in visualforce.

<p>Lorem ipsum dolor <apex:outputText value="{!map['foo test'].field1}"/>. <br/>
Neque porro quisquam est qui dolorem <apex:outputText value="{!map['bar test2'].field2}"/>...
</p>
4
  • 1
    What happened i.e. exactly how did it not work?
    – Keith C
    May 22, 2019 at 13:34
  • You have a local variable called map in your constructor that hides the map property. Change Map<String, Custom_Object__c> map = new Map... to map = new Map... so you are assigning to the property in the constructor. The pattern you are using does work.
    – Keith C
    May 22, 2019 at 13:35
  • Thanks Keith, thats exactly what it was. May 22, 2019 at 13:42
  • I've posted that as an answer; accept it and then others won't be distracted thinking you still need an answer.
    – Keith C
    May 22, 2019 at 13:48

1 Answer 1

7

You have a local variable called map in your constructor that hides the map property. (See e.g. Variable shadowing for more about that.)

Change:

Map<String, Custom_Object__c> map = new Map<String, Custom_Object__c>();

to:

map = new Map<String, Custom_Object__c>();

so you are assigning to the property in the constructor, not just the local variable.

The pattern you are using - a string keyed map - does work.

You must log in to answer this question.

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