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
Gullu SfGullu Sf 

Unable to get the Id's of the selectedRows from the Lightning Datatable

Hi There,  I have a junction object that links Contact and my Custom Object. With Standard functionality (Lookup) I can link only one custom object record to Contact. My requirement is to be able to select multiple custom object records and link them to Contact record. For this I'm using a lightning Datatable to display list of custom object records. I'm successfully creating the junction object record with ContactId but I'm unable to get the Id's of selectedRows from the datatable. Below is my CMP code:- Any help is much appreciated.

@cmp:-
<aura:component controller="MailingRetriever" implements="force:hasRecordId,force:lightningQuickActionWithoutHeader" access="global">

    <!-- attributes -->
    <aura:attribute name="recordId" type="String" access="public"/>
    <aura:attribute name="data" type="Available_Mailings__c[]"/>
    <aura:attribute name="MailingforContact" type="Mailings__c" access="public"
                    default="{
                             'SObjectType': 'Mailings__c',
                             'Contact__c': '',
                             'Available_Mailing__c': ''
                             }"/>
    <aura:attribute name="columns" type="List"/>
    <aura:attribute name="filter" type="String"/>
    <aura:attribute name="selectedRow" type="Id" />
    <aura:attribute name="selectedRows" type="List"/>
    <aura:attribute name="selectedRowsCount" type="Integer" default="0"/>
        
    <!-- handlers-->
    <aura:handler name="init" value="{!this}" action="{!c.fetchAVM}"/>
    <aura:handler name="change" value="{!v.filter}" action="{!c.updateFilter}" />
    
    <div class="modal-header slds-modal__header">
        <h2 class="title slds-text-heading--medium" >Add Mailings</h2>
    </div>

      <lightning:input placeholder="Search" type="text" value="{!v.filter}" />
       
    <br/>
    <div style="height: 250px">
        <h1>Selected Rows: {!v.selectedRowsCount}</h1>
        <lightning:datatable
                aura:id="table"
                keyField="id"
                data="{! v.data }"
                columns="{! v.columns }"
                selectedRows="{!v.selectedRows}"
                onrowselection="{! c.updateSelectedText }"/>
     </div>
      <footer class="slds-modal__footer">
        <button class="slds-button slds-button_neutral" onclick="{!c.closeAction}">Cancel</button>
        <button class="slds-button slds-button_brand" onclick="{!c.createMailing}">Save</button>
      </footer>
    </aura:component>

@controller.js:-
({
    fetchAVM : function(component, event, helper) {
                
        //sets the table columns
        component.set('v.columns', [
            {label: 'Available Mailing', fieldName: 'Name', type: 'text'},
            {label: 'Mailing Type', fieldName: 'Mailing_Type__c', type: 'Picklist'},
            {label: 'FREQUENCY', fieldName: 'Frequency__c', type: 'Picklist'},
            {label: 'MAILING CODE', fieldName: 'Mailing_Code__c', type: 'text'}
        ]);
        
        //Getting the data for the data table from the helper method.
        helper.getMailing(component);
        
    },
    
    //Searching the table with the searchText entered.
    updateFilter: function(component) {
        var data = component.get("v.data"),
            term = component.get("v.filter"),
            newdata = data.filter(word => (!term));
        component.set("v.data", newdata);
    },
    
    // gets the selected rows count and sets the value for selectedRowsCount
    updateSelectedText : function(cmp, event){
        var selectedRows = event.getParam('selectedRows');
        cmp.set("v.selectedRowsCount", selectedRows.length);
    },
    
    //Saves the record for Mailing__c Object
    createMailing : function(cmp, event, helper){
        helper.insertMailing(cmp, event, helper);       
        
    },
    
    closeAction : function(cmp, event, helper){
        $A.get("e.force:closeQuickAction").fire();
    }
})

@helper.js
({
    //Data is getting retireved from the controller method
    getMailing : function(component) {
        var action = component.get("c.getAVMData");
        action.setCallback(this, function(response){
            var state = response.getState();
            if(state == "SUCCESS"){
                component.set("v.data",response.getReturnValue());
            }
            else{
                console.log("Failed with state" + state);
            }
        });
        $A.enqueueAction(action);
    },
    
    insertMailing : function(cmp, event, helper){
        var MailingforContact = cmp.get("v.MailingforContact");
        //var selectedRowsIds = cmp.get("v.selectedRows");
        
        MailingforContact.Contact__c = cmp.get("v.recordId");    
        //MailingforContact.Available_Mailing__c = cmp.get("v.selectedRows"); // This is where I'm stuck, Not able to get the Id's of the selectedRows(List) and assign it to lookup field in the junction object.           
        var toastEvent = $A.get('e.force:showToast');
        var createAction = cmp.get("c.createMailingRec");
        
        createAction.setParams({
            mailingRec: MailingforContact
        });
        
        createAction.setCallback(this, function(response){
           var state = response.getState();
            if(state === 'Success'){
                var dataMap = response.getReturnValue();
                if(dataMap.status == 'Success'){
                    toastEvent.setParams({
                        'title': 'Success!',
                        'type': 'Success',
                        'mode': 'dismissable',
                        'message': dataMap.message
                    });
                    toastEvent.fire();
                }else if(dataMap.status == 'Error'){
                    toastEvent.setParams({
                        'title': 'Error',
                        'type': 'error',
                        'mode': 'dismissable',
                        'message': dataMap.message
                    });
                    toastEvent.fire();
                }
                    } else {
                        alert('Error in getting data');
                    }
        });
            $A.enqueueAction(createAction);
            $A.get("e.force:closeQuickAction").fire();
            $A.get("e.force:refreshView").fire();
    }
    
})

@Apex Controller:-
public class MailingRetriever {
    
    //Get Available Mailings List
    @AuraEnabled
    public static List<Available_Mailings__c> getAVMData(){
        
        List<Available_Mailings__c> avm = ([select id,Name,Frequency__c, Mailing_Code__c, Mailing_Type__c from Available_Mailings__c ]);
        return avm;
        
    }
    
    //Creats a new Mailing Record
    @AuraEnabled
    public static Map<String, String> createMailingRec(Mailings__c mailingRec){
        Map<String, String> resultMap = new Map<String, String>();
        try{
            insert mailingRec;
            resultMap.put('status', 'Success');
            resultMap.put('message', 'Mailing Inserted Successfully');
        }
        catch (Exception e){
            resultMap.put('status', 'Error');
            resultMap.put('message', e.getMessage());
        }
        
        return resultMap;
    }
}