dackdive's blog

新米webエンジニアによる技術ブログ。JavaScript(React), Salesforce, Python など

[Salesforce]VisualforceのvalueにMapを使う

ちょいメモ。
VisualforceでMapオブジェクトの値を表示したい時は

{!Mapオブジェクト名[キー名]}

で取得可能。

以下はサンプル。

Apex側

public class MapValueSampleController {
    public Map<String,String> sampleMap {
        get {
            return new Map<String, String> {
                'foo' => 'bar', 
                'hoge' => 'piyo'
            };
        }
        set;
    }
}

Visualforce側

<apex:page controller="MapValueSampleController">
    <apex:outputText value="{!sampleMap[foo]}" />
</apex:page>

特徴

  • 指定したキーに該当する値がなかった時
    Visualforce側でエラーが発生する
<apex:page controller="MapValueSampleController">
    <!-- これは表示した時にエラー -->
    <apex:outputText value="{!sampleMap[fuga]}" />
</apex:page>


  • キーにnullを指定してもエラーは発生せず、空白になる。
<apex:page controller="MapValueSampleController">
    <!-- エラーも出ないし、何も表示されない -->
    <apex:outputText value="{!sampleMap[null]}" />
</apex:page>


  • SObjectのMapとかも問題なく使える
<apex:page controller="MapValueSampleController">
    <!-- sampleMap2がMap<String, Account>だったりすると -->
    <apex:outputText value="{!sampleMap2[accountId].Name}" />
</apex:page>


  • apex:repeatとかでも使える

リファレンス

Salesforce Developers