コントローラ拡張の作成
コントローラ拡張は、ApexPages.StandardController または CustomControllerName 型の単一の引数を取るコンストラクタが含まれる Apex クラスです。CustomControllerName は、拡張するカスタムコントローラの名前です。
次のクラスは、コントローラ拡張の単純な例です。
1public class myControllerExtension {
2
3 private final Account acct;
4
5 // The extension constructor initializes the private member
6 // variable acct by using the getRecord method from the standard
7 // controller.
8 public myControllerExtension(ApexPages.StandardController stdController) {
9 this.acct = (Account)stdController.getRecord();
10 }
11
12 public String getGreeting() {
13 return 'Hello ' + acct.name + ' (' + acct.id + ')';
14 }
15}次の Visualforce マークアップは、上記のコントローラ拡張をページ内で使用する方法を示します。
1<apex:page standardController="Account" extensions="myControllerExtension">
2 {!greeting} <p/>
3 <apex:form>
4 <apex:inputField value="{!account.name}"/> <p/>
5 <apex:commandButton value="Save" action="{!save}"/>
6 </apex:form>
7</apex:page>拡張は、<apex:page> コンポーネントの extensions 属性を使用してページに関連付けられます。
すべてのコントローラメソッドと同様に、ページマークアップで {! } 表記を使用して、コントローラ拡張メソッドを参照できます。上記の例では、ページ上部の {!greeting} 式は、コントローラ拡張の getGreeting メソッドを参照しています。
この拡張は、Account 標準コントローラと共に機能するため、標準コントローラメソッドも利用できます。たとえば、<apex:inputField> タグの value 属性は、標準コントローラ機能を使用して取引先の名前���取得します。同様に、<apex:commandButton> タグは、action 属性のある標準 Account の save メソッドを参照します。
カンマ区切りのリストを使って、単一のページに対し複数のコントローラ拡張を定義できます。これにより、同じ名前のメソッドを上書きできます。たとえば、次のようなページがあったとします。
さらに、次の拡張があったとします。
<apex:outputText> コンポーネントの値は、foo-One として表示されます。上書きは、一番左の拡張、つまりカンマ区切りリストの最初の拡張で定義されているメソッドによって定義されます。したがって、ExtOne の getFoo メソッドは、ExtTwo のメソッドを上書きします。
1<apex:page standardController="Account"
2 extensions="ExtOne,ExtTwo" showHeader="false">
3 <apex:outputText value="{!foo}" />
4</apex:page>1public class ExtOne {
2 public ExtOne(ApexPages.StandardController acon) { }
3
4 public String getFoo() {
5 return 'foo-One';
6 }
7}1public class ExtTwo {
2 public ExtTwo(ApexPages.StandardController acon) { }
3
4 public String getFoo() {
5 return 'foo-Two';
6 }
7}