+ Start a Discussion
Lalitha Pavani Rallabandi 13Lalitha Pavani Rallabandi 13 

Dynamic sObject Query

Hi,
I am trying to fetch the object name dynamically from the key prefix of current recordID. I am able to get the fields dynamically using a lightning component from every sobject. I tried to fetch the record names and I succeeded. From the same I trying to fetch the duplicate records upon clicking a button on the record page. 

Scenario: Upon clicking the button on the record page, it should redirect to the other tab/window and display similar kinds of records with the record name. Here I wrote two SOQLs. 

1. Fetch the record names
2. T fetch the duplicate records based on name.

Here, I wrote a soql query and it is returning the list of records available on the object in a lightning component. Now I want to store the record name in a variable. Here I am getting the error:
 Here is the code I wrote:
 

public class LightningSchemaGlobalDescribe {
    
    @AuraEnabled
    public static list<sobject> fetchlables(String recordIdOrPrefix){
        List<String> objFields = new  List<String>();
        list<string> fields = new  list<string>();
        list<string>    fieldvalues = new list<string>();
        list<sobject> records;
        
        String objectName = '';
        list<Sobject> lists;
        try{
            
            String myIdPrefix = String.valueOf(recordIdOrPrefix).substring(0,3); 
            
            
            Map<String, Schema.SObjectType> gd =  Schema.getGlobalDescribe(); 
            
            
            for(Schema.SObjectType stype : gd.values()){
                
                
                Schema.DescribeSObjectResult r = stype.getDescribe();
                
                String prefix = r.getKeyPrefix();
                
                if(prefix!=null && prefix.equals(myIdPrefix)){
                    
                    objectName = r.getName();
                    
                    String getRecordNameQuery= 'Select Id,name from '+ objectName +' WHERE ' +' id = :recordIdOrPrefix ';
                    
                    //	lists= Database.query(getRecordNameQuery);
                    
                    //	system.debug(lists);
                    
                    String sObjectName = objectName;
                    Schema.SObjectType t = Schema.getGlobalDescribe().get(sObjectName);
                    SObject s = t.newSObject();
                    system.debug(s);
                    //we are storing names of the Object
                    lists= Database.query(getRecordNameQuery);
                    
                    system.debug(lists);
                    
                    string recordname=lists.name;  
                    
                    if(objectName!=null){
                        Map<String, Schema.SObjectField> efields = Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap();
                        
                        list<string> editableFields = new list<string> ();
                        
                        
                        for(schema.SObjectField editfieds :efields.values()){
                            
                            schema.DescribeFieldResult fieldResult = editfieds.getDescribe();
                            
                            
                            if(fieldResult.isUpdateable() ){
                                
                                editableFields.add(fieldResult.getName());
                                
                                objFields = new List<String>(editableFields);
                                system.debug('editableFields::' + editableFields);
                                system.debug('objFields::' + objFields);
                                string fieldnamess = 'SELECT '+ objFields + ' FROM '+ objectName + ' WHERE  Name LIKE %'+lists ;	
                                list<Sobject> listoffields = Database.query(fieldnamess);
                                system.debug(listoffields); 
                                
                                // system.debug('Fields:::'+objFields);
                                
                            }
                            
                            
                        }
                        
                    }  
                    
                }
                
            }
            
        }
        
        
        catch(Exception e){
            //print the error message
            System.debug(e);
        }
        return lists;
    }
    
    
}
I am getting the following error:
User-added image

Please help me with this
 

ShirishaShirisha (Salesforce Developers) 
Hi Lalitha,

Greetings!

This should not be causing the issue but still I would request to try with the Name instead of name to store the list of names in String.

Also,I would suggest you to create an array of Strings as the lists can contain more than one record.

Kindly let me know if it helps you and close your query by marking it as best answer so that it can help others in the future.

Warm Regards,
Shirisha Pathuri
Lalitha Pavani Rallabandi 13Lalitha Pavani Rallabandi 13
Hi @Shirisha,
I got the error. Now I have another issue is, I am trying to display the duplicate record names on a component based on the current record name. For that, I wrote the following code
public class LightningSchemaGlobalDescribe {
    
    @AuraEnabled
    public static list<sobject> fetchlables(String recordIdOrPrefix){
        List<String> objFields = new  List<String>();
        list<string> fields = new  list<string>();
        list<string>    fieldvalues = new list<string>();
        list<sobject> records;
        string recordsname;
        String objectName = '';
        list<Sobject> lists;
        list<sObject> listoffields;
        try{
            
            LightningSchemaGlobalDescribe.duplicateRecord(objFields,objectName,recordsname);
            String myIdPrefix = String.valueOf(recordIdOrPrefix).substring(0,3); 
            Map<String, Schema.SObjectType> gd =  Schema.getGlobalDescribe(); 
            
            for(Schema.SObjectType stype : gd.values()){
                
                
                Schema.DescribeSObjectResult r = stype.getDescribe();
                
                String prefix = r.getKeyPrefix();
                
                if(prefix!=null && prefix.equals(myIdPrefix)){
                    
                    objectName = r.getName();
                    
                    String getRecordNameQuery= 'Select Id,name from '+ objectName +' WHERE ' +' id = :recordIdOrPrefix ';
                    
                    lists= Database.query(getRecordNameQuery);
                    
                    //  system.debug(lists);
                    
                    
                    String sObjectName = objectName;
                    Schema.SObjectType t = Schema.getGlobalDescribe().get(sObjectName);
                    SObject s = t.newSObject();
                    // system.debug(s);
                    List<sObject> result= Database.query(getRecordNameQuery);
                    
                    // system.debug(result);
                    
                    
                    recordsname=string.valueof(lists[0].get('name'));
                    
                    if(objectName!=null){
                        Map<String, Schema.SObjectField> efields = Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap();
                        
                        list<string> editableFields = new list<string> ();
                        
                        
                        for(schema.SObjectField editfieds :efields.values()){
                            
                            schema.DescribeFieldResult fieldResult = editfieds.getDescribe();
                            
                            
                            if(fieldResult.isUpdateable() ){
                                
                                editableFields.add(fieldResult.getName());
                                
                                objFields = new List<String>(editableFields);
                                
                                
                                
                                //system.debug('Fields:::'+objFields); 
                            }
                            
                        }
                        
                    }  
                    
                }
                
            }
            system.debug(listoffields.size());
        }
        
        
        catch(Exception e){
            //print the error message
            System.debug(e);
            System.debug('Exception e '+e.getLineNumber());
        }
        
        
        return lists;
        
    }
    
    @AuraEnabled
    public static list<sobject> duplicateRecord(  List<String> objFields,  String objectName, string recordsname ){
        String separator = ', ';
        list<sObject> listoffields;
        string fieldnamess = 'SELECT '+ String.join(objFields, separator) + 
            				 ' FROM '+ objectName + 
                             ' WHERE Name LIKE \'' + recordsname +  '%\'';	
        
        listoffields = Database.query(fieldnamess); 
        
        return listoffields;
    }
    
    
    
}

Using Application Events, I am trying to display the duplicate record names on a lightning component similar to the current record name.
Here is my component
User-added image 
When I click on the Merge duplicate button, it should redirect to the other component and display the duplicate record names like Chantal Smith.

This is my event: NavEvent
<aura:event type="APPLICATION" >

    <aura:attribute name="recordId" type="String"/>
</aura:event>

This is my Component1: NavigateCmp1 which should redirect to the other component:
<aura:component implements="lightning:isUrlAddressable,force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global">
    <aura:attribute name ="recordId" type="String"/>
     <aura:registerEvent name="Navigator" type="c:NavEvent"/>
    
    <lightning:button label="Merge Duplicates" variant="brand" onclick="{!c.click}" aura:id="n1"/>
   
</aura:component>

Controller::
({
	click : function(component, event, helper) {
		helper.clicks(component, event, helper);
	}
})
Helper:
({
    clicks : function(component, event, helper) {
        
        
        var appEvent = $A.get("e.c:NavEvent"); 
        //Set event attribute value
        appEvent.setParams({
            "recordId" : component.get('v.recordId'),
        }); 
        appEvent.fire(); 
        
        
        var navigateEvent = $A.get("e.force:navigateToComponent");
        navigateEvent.setParams({
            componentDef: "c:NavigateCmp2",
            
        });
        navigateEvent.fire();
    }
})

Component 2: NavigateCmp2
 
<aura:component controller="LightningSchemaGlobalDescribe" implements="lightning:isUrlAddressable,force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    
    <aura:attribute name="sobj" type="sObject[]"/>
    <aura:attribute name="data" type="String[]"/>
    <aura:attribute name="columns" type="List[]" />
    <aura:attribute name="ObjectName" type="sObject[]" />
    <aura:attribute name="DuplicateRecords" type="String[]"/>
    
    <lightning:navigation aura:id="navService"/>
    
  <aura:handler event="c:NavEvent" action="{!c.component2Event}"/>
    
  <aura:handler name="init" value="{! this }" action="{! c.duplicateRecords }"/>
    
    <div class="slds-box slds-theme_default">
        <lightning:layout horizontalAlign="space" verticalAlign="center" multipleRows="true">
            <aura:iteration items="{!v.sobj}" var="mapKey">
                <lightning:layoutItem flexibility="auto" size="12" smallDeviceSize="6" mediumDeviceSize="6" largeDeviceSize="6">
                    {!mapKey.Name} <br/>
                </lightning:layoutItem>
            </aura:iteration>
            <aura:iteration items="{!v.DuplicateRecords}" var="mapKey">
                <lightning:layoutItem flexibility="auto" size="12" smallDeviceSize="6" mediumDeviceSize="6" largeDeviceSize="6">
                    {!Name} <br/>
                </lightning:layoutItem>
            </aura:iteration>
        </lightning:layout>
    </div> 
    
</aura:component>

I really don't understand to write a method on the controller to display the duplicate record name. Here is the controller

The Component2Event is displaying the current record name based on the current record ID
({
   component2Event : function(component, event, helper){
        
       var evnt = event.getParam("recordId"); 
        console.log('evnt::' +evnt);
       component.set("v.recordId",evnt );
        
      var fields = component.get('v.sobj');
      var action=component.get("c.fetchlables");
        
        action.setParams({
            "recordIdOrPrefix":evnt
        });
        
        action.setCallback(this,function(response){
            var state=response.getState();
        
           if(state==='SUCCESS'){
                var result=response.getReturnValue();
                console.log('The Result-->' + result );
                console.log(JSON.stringify(result));
                component.set("v.recordId", response.getReturnValue());
              component.set('v.sobj',result);
                 console.log('Success:::',state);
            } else if(state==='ERROR'){
              
            } 
            
        });
        $A.enqueueAction(action);
    },
    
       
    
    
    })
My issue is with the duplicaterecords method. I could not able to figure out how to write the method to display the duplicate records. 
duplicateRecords: function(component, event, helper){
           var evnt = event.getParam("recordId"); 
        var objFields = component.get("v.objFields");
        var objectName = component.get("v.objectName");
        var recordsname = component.get("v.recordsname")
         
         var action=component.get("c.duplicateRecord");
          component.set("v.recordId",evnt );
       
        
         action.setParams({
            "objFields":objFields,
             "objectName":objectName,
             "recordsname": recordsname
        });
          action.setCallback(this,function(response){
            var state=response.getState();
          
            if(state==='SUCCESS'){
                  var result=response.getReturnValue();
                console.log('The Result-->' + result );
                console.log(JSON.stringify(result));
                component.set("v.recordId", response.getReturnValue());
              
                component.set('v.DuplicateRecords',result);
                
               
            } else if (response.state === "ERROR") {
             
                var errMsg = "";
        
                for (var i = 0; i < response.error.length; i++) { 
                   
                    errMsg += response.error[i].message + "\n"; 
                }  
            }
        });
        $A.enqueueAction(action);
    }

Please help me out in writing the method to display the duplicate records