1

I am grinding my way through the art of lightning components. I am trying to achieve the following:

While being on a record, I want to see another (similiar) record based on a couple of criteria. For example 'JobTitle__c' so that in my lightning card I want to see a record who has the same 'JobTitle__c'as the record I am currently on.

enter image description here

Unfortunately I always come back to the same problem: How can I query dynamically for records based on 'JobTitle__c'

All I can find online is

action.setParams({
    
    recordId: component.get("v.recordId")

which is not getting me anywhere since it is not the recordId I need but in this case 'JobTitle__c'

Here is my apex class:

public class NextBestPotentialController {
@AuraEnabled
public static List<Lead> getLead (String JobTitle, Id recordId){
String searchTitle = '%' + JobTitle + '%';       
List<Lead> returnlead = new List<Lead>(); 
List<Lead>  myLeads = [SELECT Id,Name,JOB_Titel_letzte_bez_rel_Anzeige__c,company,city
    FROM Lead
    WHERE JOB_Titel_letzte_bez_rel_Anzeige__c LIKE :searchTitle AND Id != :recordId
    LIMIT 1
    
    ];
    
    for(Lead le:myLeads){
    returnlead.add(le);
    } 
    return returnlead ;   }}

my component:

<aura:component controller="NextBestPotentialController" implements="flexipage:availableForRecordHome,force:hasRecordId" access="global">

<aura:attribute name="JobTitle" type="String" default="Physio"/>
<aura:attribute name="leadList" type="list" />
<aura:attribute name="recordId" type="Id" />

<aura:handler name="init" value="{!this}" action="{!c.doInit}" />


<div class="slds-grid slds-wrap">
    <aura:iteration items="{!v.leadList}" var="lea"  >
<div class="slds-col slds-size_4-of-4 slds-p-around_small">
    <lightning:card title="Lead Information" footer="Sample footer" iconName="standard:lead">

        <p class="slds-p-horizontal_small">
 ID: {!lea.Id}
       </p>
       <p class="slds-p-horizontal_small">  
Name: {!lea.Name}
        </p> 
            <p class="slds-p-horizontal_small">
 Firma: {!lea.Company}
            </p>
           <p class="slds-p-horizontal_small">
Jobtitle: {!lea.JOB_Titel_letzte_bez_rel_Anzeige__c}
         </p> 
        <aura:set attribute="footer">
        <lightning:badge label="Tag1"/>
        <lightning:badge label="Tag2"/>
        <lightning:badge label="{!lea.JOB_Titel_letzte_bez_rel_Anzeige__c}"/>
    </aura:set>
    </lightning:card>
</div> 


    </aura:iteration>
    </div>
  </aura:component>

my controller:

({
 doInit : function(component, event) {

    var action  = component.get('c.getLead');

     action.setParams({
    
    recordId: component.get("v.recordId"),
    JobTitle: component.get("v.JobTitle")
   
});

     action.setCallback(this,function(response){
    var state=response.getState();
    var response1=response.getReturnValue();
    if(state==="SUCCESS")
    {
        component.set("v.leadList",response1);
    }
   
});
$A.enqueueAction(action); }})

So the only reason why I get a result is because I set a default on

<aura:attribute name="JobTitle" type="String" default="Physio"/>

Otherwise it would be null since I dont know how, where and when to populate the values.

1 Answer 1

2

This is pretty simple. You'd need JobTitle of the current record & a SOQL to get records related to it.

  1. Just implement your aura component with force:hasRecordId & you'll get record id of the current record.
  2. Use LDS(Lightning data service) to get JobTitle field of the current record).
  3. Make an Apex call to get the related records.

For the reference you've to do something like,

---NextBestPotential.cmp---

<aura:component access="GLOBAL" implements="flexipage:availableForAllPageTypes, force:hasRecordId" controller="NextBestPotentialController">
    <aura:attribute name="accountRecord" type="Object"/>
    <aura:attribute name="relatedRecords" type="List"/>
    <aura:attribute name="recordLoadError" type="String"/>
    <force:recordData aura:id="recordLoader"
    recordId="{!v.recordId}"
    fields="Name,Description,Phone"
    targetFields="{!v.accountRecord}"
    targetError="{!v.recordLoadError}"
    recordUpdated="{!c.handleRecordUpdated}"
    />
<!-- Display Lightning Data Service errors, if any -->
<aura:if isTrue="{!not(empty(v.recordError))}">
    <div class="recordError">
        {!v.recordError}</div>
</aura:if>
</aura:component>

---NextBestPotentialController.js---

({
      handleRecordUpdated : function(c, e, h){
        var eventParams = e.getParams();
        if(eventParams.changeType === "LOADED") {
           // record is loaded (render other component which needs record data value)
            console.log("Record is loaded successfully.");
            h.getRelatedRecords(c, e, h);
        } else if(eventParams.changeType === "CHANGED") {
            // get the fields that changed for this record
            var changedFields = eventParams.changedFields;
            console.log('Fields that are changed: ' + JSON.stringify(changedFields));
        } else if(eventParams.changeType === "REMOVED") {
            // record is deleted
        } else if(eventParams.changeType === "ERROR") {
            // there’s an error while loading, saving, or deleting the record
        }
      }
    });

---NextPotentialHelper.js---

({
  getRelatedRecords: function (component, event, helper) {
    const action = component.get("c.getRecordBasedonJobTitle");
    console.log("::Name:: >", component.get("v.accountRecord.Name"));
    action.setParams({ jobTitle: component.get("v.accountRecord.Name") });
    action.setCallback(this, function (response) {
      if (response.getState() === "SUCCESS") {
        component.set("v.relatedRecords", response.getReturnValue());
      } else {
        console.log("::some error::::");
      }
    });
    $A.enqueueAction(action);
  }
});

And, NextPotentialController.cls

@AuraEnabled
public static List<Lead> getRecordBasedonJobTitle(String jobTitle){
    return [
        SELECT Name FROM Lead WHERE Title__c LIKE : jobTitle
    ];
}
6
  • Hello @Sachin thanks for your reply. I get that it should be easy but I am still struggling as no results show up when I create my lightning card. I am still not sure if this actually helps me. Lets say I am currently on an 'account' but I want to see 'lead' records with the same jobTitle as the one from the account. The query does not seem to get 'triggered' The query wil be on the lead object right? How does that work with defining the fields to display in force:recordData?!
    – Jan Tonnet
    Dec 27, 2020 at 7:19
  • 1
    Yes, in the case the SOQL should be on Lead. force:Data pulls the record with the specified id we mentioned in recordId, targetFields would be the fields we needed, just like a SOQL, whenever the state of the data changes, the function defined on recordUpdated will be fired. Since we need to get related records based on one of the field. Once the field value is available we can query lead records similar to it. Dec 27, 2020 at 7:25
  • Still wondering. Can you give a snippet of how you would display the retrieved data from your example above in a lightning card?
    – Jan Tonnet
    Dec 27, 2020 at 7:45
  • 1
    You already have it good. Simply replace component.set("v.relatedRecords", response.getReturnValue()); to component.set("v.leadList", response.getReturnValue()); . response.getReturnValue() contains the related lead records with similar Job title. Dec 27, 2020 at 7:52
  • Haha. I replaced my code with yours. So it was not all Wrong when I have to refer to leadlist now?
    – Jan Tonnet
    Dec 27, 2020 at 8:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .