function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
User One 35User One 35 

Display all Child Records on Parent Object

I want to display all child records on parent object  here is my code 
But it displaying only contact records, I want to display all records which related to the parent object (it means all child objects records should display in parent Account object) please help me how to use triggers here.

Apex Code:
public class ContactsRecordsToAccounts{
  
    Public Id accID;
    public List<Contact> contactList{get;set;}
    public ContactsRecordsToAccounts(){
   contactList = new List<Contact>();
   accID=  ApexPages.currentPage().getParameters().get('acId');
   contactList =  [SELECT FirstName,LastName,Email,Phone FROM Contact WHERE AccountID = : accID];
 }
}

Visualforce Page Code:

<apex:page controller="ContactsRecordsToAccounts" sidebar="false" showHeader="false">
     <apex:pageBlock >
           <apex:pageBlockTable value="{!contactList}" var="con">
                      <apex:column value="{!con.FirstName}"/>
                       <apex:column value="{!con.LastName}"/>
                       <apex:column value="{!con.Phone}"/>
                       <apex:column value="{!con.Email}"/>
           </apex:pageBlockTable>
        </apex:pageBlock>
</apex:page>
Best Answer chosen by User One 35
PrabhaPrabha
I need to provide some background to get to the answer properly.

Simply: Triggers are not meant to control the UI elements. 

The purpose of triggers is to automate the process upon the events like insert, update, delete and undelte. they only handle the data in ur system. No other business.
It can also be said "There is no other way you can use trigger logic without making a DML." 
That is why the syntax has a mendatory aspect of BEFORE_EVENT and AFTER_EVENT.

Things TRIGGERS can do upon those DML statements, some:
  • It can create related data or any data for that matters,
  • It can Query the database and update data, not to mention the deletes etc,
  • It is synchronous
The list goes on...

Things TRIGGERS cannot do, some:
  • Redirect the user to different page based on value
  • Callout during the save/ delete, so developers use the workaround
  • Show and Hide certain data elements on the record (Your case here)
Salesforce has given other solutions for other challenges.
If you want to show all the child records on parents, bring them all on pagelayout. if you want to show more records, click on "show more" link below on the related list.

Let me know what is the business case here.

PrabhaN
 

All Answers

PrabhaPrabha
First of all, a very important thing if that is not a mistake in your question:
"What you have is an apex class (Controller/ extention class), NOT trigger."
It is easy to identify the difference, triggers have the word "trigger" in the first line and so is for class.

Now getting into the details, There's couple of ways you can do this.
  1. Easy way, I like the most, is by using Standard controller where you dont need write Apex at all, here is a sample code: 
    <apex:page standardController="Account" sidebar="false" showHeader="false">
        <apex:pageBlock title="Related Records">
            <apex:pageBlockSection  title="Contacts"   >
                <apex:pageBlockTable value="{!Account.Contacts}" var="con">
                    <apex:column value="{!con.FirstName}"/>
                    <apex:column value="{!con.LastName}"/>
                    <apex:column value="{!con.Phone}"/>
                    <apex:column value="{!con.Email}"/>
                </apex:pageBlockTable>
            </apex:pageBlockSection> 
            <apex:pageBlockSection  title="Opportunities"   >
                <apex:pageBlockTable value="{!Account.Opportunities}" var="con">
                    <apex:column value="{!con.Name}"/>
                    <apex:column value="{!con.StageName}"/>
                    <apex:column value="{!con.Closedate}"/>
                    <apex:column value="{!con.Description}"/>
                </apex:pageBlockTable>
            </apex:pageBlockSection> 
        </apex:pageBlock>
    </apex:page>
  2. Your way: your code works for contacts only as you are querying only contacts .
You will need all those queries that you want to display on the page.

For example, if you want to display Opportunities, Task and all other objects in the VF page, you need to have the same patterns repeated as you did for Contacts.
 
Let me know if that doesnt help!

PrabhaN
 
PrabhaPrabha
  • One more thing if you are going with option1: Your URL will have to have 'id' instead of 'acId'. StandardController detects 'id' and takes care of the rest for you.
PrabhaN
User One 35User One 35
Hi Prabha,
Yes, I am using class not trigger my question how to use a trigger to display all child records should display in the parent object. forget about Visualforce page and apex code which I mention. I want to start another way that using triggers 
User One 35User One 35
Please, can anyone help me on this I want to display all child records in parent object by using triggers,  I have tried using Visualforce page and apex to display all child records in parent object.
 
PrabhaPrabha
Did you try theexample I gave above? It should give you want you wanted.

PrabhaN
User One 35User One 35
Yeah, I tried Prabha all examples are working do you have any idea about how to do triggers to get the same output.

 
PrabhaPrabha
I need to provide some background to get to the answer properly.

Simply: Triggers are not meant to control the UI elements. 

The purpose of triggers is to automate the process upon the events like insert, update, delete and undelte. they only handle the data in ur system. No other business.
It can also be said "There is no other way you can use trigger logic without making a DML." 
That is why the syntax has a mendatory aspect of BEFORE_EVENT and AFTER_EVENT.

Things TRIGGERS can do upon those DML statements, some:
  • It can create related data or any data for that matters,
  • It can Query the database and update data, not to mention the deletes etc,
  • It is synchronous
The list goes on...

Things TRIGGERS cannot do, some:
  • Redirect the user to different page based on value
  • Callout during the save/ delete, so developers use the workaround
  • Show and Hide certain data elements on the record (Your case here)
Salesforce has given other solutions for other challenges.
If you want to show all the child records on parents, bring them all on pagelayout. if you want to show more records, click on "show more" link below on the related list.

Let me know what is the business case here.

PrabhaN
 
This was selected as the best answer
User One 35User One 35
Thanks Prabha for your valuable time and Effort. Could you please help me with this code I am getting some errors 

In Visualforce page  Error: Unknown property 'String.Name'
Apex Error: Compile Error: Unexpected token 'accID'. at line 9 column 4

Apex:
public class ContactsRecordsToAccounts{
  
    Public Id accID;
    public List<Contact> contactList{get;set;}
    public List<Opportunities>opprList{get;set;}
    public ContactsRecordsToAccounts(){
   contactList = new List<Contact>();
   opprList = new List<Opportunities>
   accID=  ApexPages.currentPage().getParameters().get('acId');
   contactList =  [SELECT FirstName,LastName,Email,Phone FROM Contact WHERE AccountID = : accID];
   opprList = [SELECT Name, Account, Owner Type FROM Opportunities WHERE AcountID = :accID];
 }
}

Visualforce Page:
<apex:page controller="ContactsRecordsToAccounts" sidebar="false" showHeader="false">
    <apex:pageBlock >
       <apex:pageblocksection title="Contacts">
            <apex:pageBlockTable value="{!contactList}" var="con">
                <apex:column value="{!con.FirstName}"/>
                <apex:column value="{!con.LastName}"/>
                <apex:column value="{!con.Phone}"/>
                <apex:column value="{!con.Email}"/>
             </apex:pageBlockTable>
        </apex:pageblocksection>
            <apex:pageblocksection title="Opportunities">
                <apex:pageblocktable value="{!opprList}" var="op">
                    <apex:column value="{!op.Name}"/>
                    <apex:column value="{!op.Account}"/>
                    <apex:column value="{!op.Owner}"/>
                    <apex:column value="{!op.Type}"/>
                </apex:pageblocktable>
            </apex:pageblocksection>
    </apex:pageBlock>
    
</apex:page>
 
PrabhaPrabha
In the line "opprList = new List<Opportunities>" , you need to add '();' like in previous line.

Also, The query " opprList = [SELECT Name, Account, Owner Type FROM Opportunities WHERE AcountID = :accID]; " needs to read as follows:
opprList = [SELECT Name, Account, Ownerid, Type FROM Opportunities WHERE AcountID = :accID];

PrabhaN
User One 35User One 35
Hi Prabha 
Is there any chance to display record count in parent object using Triggers, if yes please help me with that also. I am new to coding  due to that too many questions for you 
PrabhaPrabha
Yes, there is. In a nutshell what you are trying to do is creating rollup summary fields on parent. But SF allows only on Opportunities. you need to create custom code/ triggers for contacts or any other child objects count.

Here is an example I found on forums, modified for ur requirement:
Trigger on Opportunity:
trigger newLeadTrigger on Opportunity (after insert , after update, after delete , after undelete) {
    
    if(trigger.isAfter && (trigger.isInsert || trigger.isUpdate || trigger.isUndelete)){
   		OpportunityCustomRollup.CountRollup(Trigger.new);
    }
    
    if(Trigger.isDelete)
    {
        OpportunityCustomRollup.CountRollup(Trigger.old);
    }
}

The class:
public class OpportunityCustomRollup {
   
	public static void CountRollup(List<Opportunity> lstOpportunity){
        
        Set<Id> accset = new set<Id>();
		try {
                for (Opportunity opp : lstOpportunity){
                    if( !accOppCoountMap.containsKey(opp.AccountId)) {
                         accOppCoountMap.put(opp.AccountId,0)
}

                }

            list<Account> accs = new List<account>();
            AggregateResult[] counts  =[select  accountid, count(id) opps
                                  from Opportunity 
                                  where accountid in : ids
                                   group by accountid];
                 for(AggregateResult ar : counts){
                     account acc = new account(Id=string.valueof(ar.get('accountId')),your_custom_field__c=integer.valueof(ar.get('opps')));
                     accs.add(acc); 
                 }
             
                  if(accs.size()>0) update accs;
            } 
       
        
        catch (Exception e) {
                System.debug(e);
            }
        
	}

}

PrabhaN