1

I have this requirement to get all child records only of a parent record. There is no error in the code. i'm able to display the data using below code but. i want to display the same output using lightning-datatable.

HTML code


         <template if:true ={data}>   
                
                <lightning-datatable data={data} columns={columns} key-field="Id">
                </lightning-datatable>
<!--
                <template for:each={policy.Motor_Insurances__r} for:item="motorIns">
                    <p key={motorIns.Id}>{motorIns.Name}</p>
                    <p key={motorIns.Id}>{motorIns.Premium_Type__c}</p>
                    <p key={motorIns.Id}>{motorIns.Premium_Amount__c}</p>
                    <p key={motorIns.Id}>{motorIns.Due_Date__c }</p>
                </template>
 
                <template for:each={policy.Life_Insurances__r} for:item="lifeIns">
                    <p key={lifeIns.Id}>{lifeIns.Name}</p>
                    <p key={lifeIns.Id}>{lifeIns.Premium_Type__c}</p>
                    <p key={lifeIns.Id}>{lifeIns.Premium_Amount__c}</p>
                    <p key={lifeIns.Id}>{lifeIns.Due_Date__c }</p>
                </template>            
                -->
                </template> 
            </template>



JS code:

import { LightningElement,api, track } from 'lwc';

import getPoliciesList from '@salesforce/apex/customSearchSobjectLWC.getPoliciesList'

import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class SearchAllPolicies extends LightningElement {

    @track columns = [{
        label: 'Policy ID',
        fieldName: 'Name',
        type: 'Auto Number',
        sortable: true
    },
    {
        label: 'Premium Type',
        fieldName: 'Premium_Type__c',
        type: 'Picklist',
        sortable: true
    },
    {
        label: 'Premium Amount',
        fieldName: 'Premium_Amount__c',
        type: 'Currency',
        sortable: true
    },
    {
        label: 'Due Date',
        fieldName: 'Due_Date__c',
        type: 'Date',
        sortable: true
    }

];


@track data;
@track error;
@track searchValue ='';

    searchKeyword(event) {
    this.searchValue = event.target.value;
    console.log(this.searchValue);
}

handleSearchKeyword(){
    if(this.searchedValue !== '') {
    getPoliciesList({
        searchKey: this.searchValue
            })
            .then(result=> {
                this.data = result;
                console.log(this.data);
            })
            .catch(error=> {
                //this.error = error;
            
                const event = new ShowToastEvent({
                    title: 'Error',
                    variant :'error',
                    message: error.body.message,
                });
                this.dispatchEvent(event);
                console.log(data); 
                //reset the data var with null
                this.data = null;
            });
        
        }//end of if
        
        else {
            const event = new ShowToastEvent({
                variant: 'error',
                message: 'Search text missing..',
            });
            this.dispatchEvent(event);  
        }

        }                                          
             
}

Orignal Apex Code:

public class customSearchSobjectLWC {

@AuraEnabled(cacheable=true)
    public static list<Policy_Holder__c> getPoliciesList(string searchKey ) {


list<Policy_Holder__c> returnResult = new list<Policy_Holder__c>();

        string searchText = '%' +searchKey + '%' ;

            for(Policy_Holder__c pH : [SELECT Id, Name, (SELECT Id,Name,Premium_Type__c,Premium_Amount__c,Due_Date__c FROM Life_Insurances__r), (SELECT Id, Name, Premium_Type__c,Premium_Amount__c,Due_Date__c FROM Motor_Insurances__r) FROM Policy_Holder__c WHERE Name LIKE : searchText]) {
                

                for(Life_Insurance__c childIns : pH.Life_Insurances__r) {

                    system.debug('Policy ID of Iife Insurance is :' +childIns.Name);
                    system.debug('Policy Type of Iife Insurance is :' +childIns.Premium_Type__c);
                    system.debug('Premium Amount of Iife Insurance is :' +childIns.Premium_Amount__c);
                    system.debug('Due Date of Iife Insurance is :' +childIns.Due_Date__c);
                }

                for(Motor_Insurance__c childMotor : pH.Motor_Insurances__r) {

                    system.debug('Policy ID of Motor Insurance is :' +childMotor .Name);
                    system.debug('Policy Type of Motor Insurance is :' +childMotor .Premium_Type__c);
                    system.debug('Premium Amount of IifeMotor Insurance is :' +childMotor .Premium_Amount__c);
                    system.debug('Due Date of Motor Insurance is :' +childMotor .Due_Date__c);
                }

                

                returnResult.add(pH);
            }

        
        system.debug(returnResult);

        if(returnResult.size()==0) {
            throw new AuraHandledException('No Record Found');
        }
        
        return returnResult;
        
        }
        


    }

Updated Apex Code:

public class customSearchSobjectLWC {

@AuraEnabled(cacheable=true)
    public static list<Policy_Holder__c> getPoliciesList(string searchKey ) {



//list<Policy_Holder__c> returnResult = new list<Policy_Holder__c>();
        string searchText = '%' +searchKey + '%' ;

            for(Policy_Holder__c pH : [SELECT Id, Name, (SELECT Id,Name,Premium_Type__c,Premium_Amount__c,Due_Date__c FROM Life_Insurances__r), (SELECT Id, Name, Premium_Type__c,Premium_Amount__c,Due_Date__c FROM Motor_Insurances__r) FROM Policy_Holder__c WHERE Name LIKE : searchText]) {
                
            List<Motor_Insurance__c> listOfMotorInsaurance = new List<Motor_Insurance__c>();
                    
            
                for(Life_Insurance__c childIns : pH.Life_Insurances__r) {

                   Motor_Insurance__c motorInsaurance = new Motor_Insurance__c();
   
                  motorInsaurance.Name = childIns.Name;
                  motorInsaurance.Premium_Type__c= childIns.Premium_Type__c;
                  motorInsaurance.Premium_Amount__c= childIns.Premium_Amount__c;
                  motorInsaurance.Due_Date__c = childIns.Due_Date__c; 

                  listOfMotorInsaurance.add(motorInsaurance);
                  

             }   
            return listOfMotorInsaurance;
            }

     
          
        
        }
        


    }

below is the output which i'm getting: enter image description here

I tried lightning-datatable but not getting data of child objects.

enter image description here

5
  • 1
    Welcome to Salesforce Stack Exchange (SFSE). Please take the SFSE Tour & look in the Help Center - especially What topics can I ask about here? where it states, "Questions that ask for the community to write code or provide step-by-step instructions for implementation are often not received well and are likely to be closed." Please edit your question to include what you have tried and how it is not working (e.g., exact errors, issues).
    – Moonpie
    Aug 31 at 19:09
  • Thank you for editing your question to add more info. That is helpful to show what you currently have. However I see no lightning-datatable code. It seems that you still asking this community to write your code for you. We are not an implementation service. Please make an attempt to display it in a lightning-datatable in LWC; if you are unsuccessful, then come back & edit your question to add code you have tried, any exact error messages, or anything it is not doing as you expect it to.
    – Moonpie
    Sep 1 at 10:21
  • Sorry! I had the datatable code already but removed it because I felt I'm totally doing wrong. I will edit and add. Thanks!
    – Amit_SFDC
    Sep 1 at 12:31
  • You may be doing it totally all wrong, but that is OK! This community exists to try to help you when that happens, not to just do it for you. :)
    – Moonpie
    Sep 1 at 12:36
  • understood. Thanks. :) I've posted the original code which I've tried but was unable to get the output as I wanted.
    – Amit_SFDC
    Sep 1 at 13:52
2

The lightning-datatable will not be able to read child records or if you run a query from child to parent the parent fields, In order to do this you have two options, you can either create a wrapper in Apex with all the fields that you want to display and pass it to LWC(which can be directly used by the datatable). OR you can pass the data to lwc and iterate over the payload in lwc, prepare a wrapper and pass it to your data table. Hope it helps you. Do let me know if you have any more questions/concerns regarding this approach.

since you want to display four fields, you can create a wrapper like below in apex and directly pass it to the data-table:

public class motorInsaurance{
    @AuraEnabled
    public String Name { get; set;}
    @AuraEnabled
    public String PremiumType { get; set;}
    @AuraEnabled
    public String PremiumAmount { get; set;}
    @AuraEnabled
    public String DueDate{ get; set;} 

}

Basically, data-table will not be able to read anything with a '.'(dot) operator.

Let's say your wrapper class is motorInsaurance, so what you can do is, while you are looping pH.Life_Insurances__r in your apex class, you can create an instance of the wrapper class, and populate it as follows:

List<motorInsaurance> listOfMotorInsaurance = new List<motorInsaurance>();
for(Life_Insurance__c childIns : pH.Life_Insurances__r) {

  motorInsaurance eachMotorInsaurance = new motorInsaurance();
   
  eachMotorInsaurance.Name = childIns.Name;
  eachMotorInsaurance.PremiumType = childIns.Premium_Type__c;
  eachMotorInsaurance.PremiumAmount = childIns.Premium_Amount__c;
  eachMotorInsaurance.DueDate = childIns.Due_Date__c; 

  listOfMotorInsaurance.add(eachMotorInsaurance);

}

And you can return the listOfMotorInsaurance to your lwc which the lightning datatable can easily read.

You can modify your apex class as follows:

public class customSearchSobjectLWC {

@AuraEnabled(cacheable=true)
public static List<PolicyHolderChildWrapper> getPoliciesList(string searchKey ) {

        
        List<PolicyHolderChildWrapper> returnResult = new List<PolicyHolderChildWrapper>();

        string searchText = '%' +searchKey + '%' ;

        for(Policy_Holder__c pH : [SELECT Id, Name, (SELECT Id,Name,Premium_Type__c,Premium_Amount__c,Due_Date__c FROM Life_Insurances__r), (SELECT Id, Name, Premium_Type__c,Premium_Amount__c,Due_Date__c FROM Motor_Insurances__r) FROM Policy_Holder__c WHERE Name LIKE : searchText]) {
            
            

            for(Life_Insurance__c childIns : pH.Life_Insurances__r) {

                PolicyHolderChildWrapper eachChild = new PolicyHolderChildWrapper();
                eachChild.childName = childIns.Name;
                eachChild.childPremiumType = childIns.Premium_Type__c;
                eachChild.childPremiumAmount = childIns.Premium_Amount__c;
                eachChild.childDueDate = childIns.Due_Date__c;
                
                returnResult.add(eachChild)
                
            }

            for(Motor_Insurance__c childMotor : pH.Motor_Insurances__r) {
            
                PolicyHolderChildWrapper eachChild = new PolicyHolderChildWrapper();
                eachChild.childName = childMotor.Name;
                eachChild.childPremiumType = childMotor.Premium_Type__c;
                eachChild.childPremiumAmount = childMotor.Premium_Amount__c;
                eachChild.childDueDate = childMotor.Due_Date__c;
                
                returnResult.add(eachChild)

            }

        }

    
    system.debug(returnResult);

    if(returnResult.size()==0) {
        throw new AuraHandledException('No Record Found');
    }
    
    return returnResult;
    
    }
 
public class PolicyHolderChildWrapper{
    @AuraEnabled
    public String childName { get; set;}
    @AuraEnabled
    public String childPremiumType { get; set;}
    @AuraEnabled
    public String childPremiumAmount { get; set;}
    @AuraEnabled
    public String childDueDate{ get; set;} 
}    

}

You would have to use 'childName', 'childPremiumType' in your lwc since those are the variables being passed.

9
  • Hi @Awais, Thanks for your reply. I've actually never used Wrapper class before and am not confident about how I will achieve using the approach which you are telling me to implement in my code :( but I will try.
    – Amit_SFDC
    Sep 2 at 7:53
  • Hi @Amit_SFDC, I have edited my answer to include a sample wrapper class, hope it helps. Do let me know if you have any more concerns/questions. Sep 2 at 8:19
  • Below line is giving me an error as Name field is standard field of Type Auto Number. eachMotorInsaurance.Name = childIns.Name; --> Error: Compile Error: Field is not writeable: Motor_Insurance__c.Name at line 21 column 39 also return listOfMotorInsaurance; --> Compile Error: Illegal conversion from List<Motor_Insurance__c> to List<Policy_Holder__c> at line 30 column 13
    – Amit_SFDC
    Sep 2 at 10:00
  • Could you attach your complete apex class so that I can look into it? Sep 2 at 10:56
  • I've added my previous Apex code and also updated Apex code(where i tried your approach) in my original post. Please check go thru it once. Thanks!
    – Amit_SFDC
    Sep 2 at 12:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.