📺
[逆引きSalesforce] オブジェクト内の選択リスト項目をVisualforceで利用するには
カスタムコントローラで実装すべきコト
選択リスト(Picklist)の内容を取得し、それを返却するVisualforce用のカスタムコントローラをApexクラスで準備します。
各オブジェクト内に定義される選択リスト項目は、getDescribe().getPicklistValues()によって、List<Schema.PicklistEntry>型で取得可能です。
特定の選択リストを取得し、List<SelectOption>型に突っ込んで return するカスタムコントローラを作成します。
SampleSelectOption.apxc
public class SampleSelectOption {
public List<SelectOption> getSources() {
// Picklist を取得 (例: 取引先オブジェクト内の 'AccountSource' 項目)
List<Schema.PicklistEntry> sourceOptions = Account.AccountSource.getDescribe().getPicklistValues();
List<SelectOption> options = new List<SelectOption>();
// 取得した Picklist を一つずつ List<SelectOption> に追加して返却する
for(Schema.PicklistEntry source: sourceOptions) {
options.add(new SelectOption(source.getValue(), source.getLabel()));
}
return options;
}
}
Visualforce側で利用できるタグ
次に Visualforce 側において、<apex:selectOptions> の value= で、カスタムコントローラのメソッドを定義します。利用可能なタグは、次の通り <apex:selectCheckboxes>, <apex:selectList>, <apex:selectRadio> の 3通りです。
コントローラ内の暗黙のget,setが未だに慣れない。
sampleSelectOptionPage.vfp
<apex:page controller="SampleSelectOption">
<apex:form>
<apex:selectCheckboxes>
<apex:selectOptions value="{!Sources}" />
</apex:selectCheckboxes>
<apex:selectList size="1" multiselect="false">
<apex:selectOptions value="{!Sources}" />
</apex:selectList>
<apex:selectRadio>
<apex:selectOptions value="{!Sources}" />
</apex:selectRadio>
</apex:form>
</apex:page>
なんの修飾もしてないので、しらふの画面ですが、こんな感じになります。

Discussion