今回は簡単な検索画面の実装について書いていきます。
salesforceの標準オブジェクトである商品(Product2)の検索を行うという設定でやっていきます。
まずは画面からです。
<apex:form>
<apex:pageBlock title="商品検索" tabStyle="Product2">
<apex:pageBlockSection columns="1">
<apex:inputText value="{!conditions.Name}" required="false"/>
<apex:inputField value="{!conditions.Family}"/>
<apex:inputField value="{!conditions.ProductCode}"/>
</apex:pageBlockSection>
<apex:pageBlockButtons location="bottom">
<apex:commandButton action="{!search}" value="検索開始"/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
検索する項目は3つに絞り、それに対してsearchボタンを配置しています。
基本的な実装になります。
それに対してのApexコードがこちらです。
public class KensakuGamenController{
/* 検索結果リスト */
public List<Product2> results {get;set;}
/* 検索条件取得用 */
public Product2 conditions {get;set;}
public KensakuGamenController(){
this.results = new List<Product2>();
this.conditions = new Product2();
}
public void search(){
try {
String conditionSql = this.getWhere();
String soql =
'SELECT '
+ 'Id,Name,Family,ProductCode '
+ 'FROM Product2 ' + conditionSql;
this.results = database.query(soql);
} catch(DmlException e) {
ApexPages.addMessages(e);
} catch(Exception e) {
ApexPages.addMessages(e);
}
}
private String getWhere() {
List<String> param = new List<String>();
if (this.conditions.Name != null) {
param.add('Name LIKE \'%' + this.conditions.Name + '%\'');
}
if (!String.isBlank(this.conditions.Family)) {
param.add('Family = \'' + this.conditions.Family + '\'');
}
if (this.conditions.ProductCode != null) {
param.add('ProductCode LIKE \'%' + this.conditions.ProductCode + '%\'');
}
if (param.isEmpty()) {
return '';
}
return 'WHERE ' + String.join(param, ' AND ');
}
}
searchボタン押下⇨conditionsに入ってきた検索結果でWhere句以下を作成⇨それを繋げてsoqlを作成
⇨クエリ発行という形です。
これも基本的な形になるかと思います。
より複雑な検索になってくるとバリデーションチェックだったりだとかも入れてもいいかもしれませんね。
そして上記の結果を表示する画面です。
今回はapex:repeatを使ってやってみました。
<table>
<thead>
<tr>
<th>商品ID</th>
<th>商品名</th>
<th>商品ファミリ</th>
<th>商品コード</th>
</tr>
</thead>
<tbody>
<apex:repeat value="{!results}" var="a">
<tr>
<td><apex:outputText value="{!a.Id}"/></td>
<td><apex:outputText value="{!a.Name}"/></td>
<td><apex:outputText value="{!a.Family}"/></td>
<td><apex:outputText value="{!a.Productcode}"/></td>
</tr>
</apex:repeat>
</tbody>
</table>
tableのヘッダーだけ固定なので先に書いておき、あとはrepeatタグに委ねるというものです。
完成しました。

うまく表示されています。
基本的な動きができていればあとは応用なので練習で作成するのにちょうどいいと思います。
ご覧いただきありがとうございました。
コメント