LoginSignup
2
1

More than 5 years have passed since last update.

Salesforce:Visualforceにて子オブジェクトの項目値を取得する方法

Last updated at Posted at 2016-10-08

オブジェクトParentがオブジェクトChildの親であるとします。
この時、Visualforceにて特定のParentの子供であるChildの項目をリスト表示する方法考えます。

前提条件

  • ParentのAPI参照名を Parent__c とします。
  • ChildのAPI参照名を Child__c とします。
  • Childは4つの項目を持ち、その内一つはParentへの参照です。この参照のAPI参照名を Child2Parent__c とします。また、子リレーション名を Children とします。
  • Childの残る3つの項目をX,Y,Zとし、それぞれのAPI参照名を X__c, Y__c, Z__cとします。

ApexでControllerを実装

パラメータで受け取ったID( ParentId )でParentを検索し、その子であるChildも取得します。
SOQLは次の通りです。

Select Id, (Select Id, X__c, Y__c, Z__c from Children__r) Where Id = :parentId Limit 1

取得したChildオブジェクト群をList型に格納します。

ExampleController
public Id parentId {get; set;}
public List<Child> children {get; set;}

public ExampleController() {
    this.children = new List<Child>();
}

public void doSearch() {
    if (String.isEmpty(parentId)) {
        return;
    }
    Parent parent = [Select Id, (Select Id, X__c, Y__c, Z__c from Children__r) Where Id = :parentId Limit 1];
    if (parent.size() > 0) {
        for (Child child : parent.Children__r) {
            this.children.add(child);
        }
    }
}

Visualforceで子オブジェクトをリスト表示

Listのchildrenを使ってVisualforce側でapex:pageBlockTableを使ってループし、各項目(X, Y, Z)を表示します。

ExampleVisualforce
<apex:page controller="ExampleController" title="ExampleVisualforce" showHeader="true" sidebar="false" id="page">
  <apex:form id="form">
    <apex:pageBlock id="block">
      <apex:pageBlockButtons >
        親(Parent)のSalesforce ID: <apex:inputText value="{!parentId}" id="parentId"/>
        <apex:commandButton value="Search" title="Search" action="{!doSearch}" reRender="form" />
      </apex:pageBlockButtons>
      <div>
      <apex:pageBlockTable value="{!children}" var="child">
        <apex:column headerValue="項目X">
          <apex:outputText value="{!child.X__c}" />
        </apex:column>
        <apex:column headerValue="項目Y">
          <apex:outputText value="{!child.Y__c}" />
        </apex:column>
        <apex:column headerValue="項目Z">
          <apex:outputText value="{!child.Z__c}" />
        </apex:column>
      </apex:pageBlockTable>
      </div>
    </apex:pageBlock>
  </apex:form>
</apex:page>

作成したVisualforceで親のSalesforce IDを指定して[Search]ボタンをクリックすると、その親が持つ子供の項目がリスト表示されます。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1