+ Start a Discussion
sumit suwalkasumit suwalka 

lightning component to remove records from list not delete

Hi All,
        i have requirement in which i want to show custom object(FBG_Family__c) records in lighning component.every record has checkbox besides it and when the checkbox is clicked that record should be removed from the list (not delete from database)component.
        how to do it?
        Any suggestions?
Best Answer chosen by sumit suwalka
Khan AnasKhan Anas (Salesforce Developers) 
Use below lines of code:
{label: 'Sister Company', fieldName: 'sc1', type: 'text'},
{label: 'Sister Company', fieldName: 'sc2', type: 'text'}
 
var allValues = response.getReturnValue();
                for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    if (row.Account) row.sc1 = row.Account.Name; // If you are using custom object then use custom object name instead of Account
                }
                console.log("allValues--->>> " + allValues);
                component.set('v.mydata', allValues);

Regards,
Khan Anas

All Answers

Khan AnasKhan Anas (Salesforce Developers) 
Hi Sumit,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement (I have used Transport custom object, you can change it to FBG Family).

Apex:
public class RemoveRecords_SvrController {

    @AuraEnabled
    public static List<Transport__c> fetchRecords() {
        return [SELECT Id, Name, Service_Date__c FROM Transport__c];
    }
}

Component:
<aura:component controller="RemoveRecords_SvrController"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" 
                access="global" >
	
    <aura:attribute name="PageHeading" type="String" default="Remove Records From Table On Click Of Check Box" />
    <aura:attribute name="mydata" type="Object"/>
    <aura:attribute name="mycolumns" type="List"/>

    
    <aura:handler name="init" value="{!this}" action="{!c.doinit}" />
    
    <div class="slds-m-top--xx-large">
    	<div class="slds-page-header">
    		<div class="slds-align--absolute-center">
        		<div class="slds-text-heading--large">       
    				{!v.PageHeading}
                </div>
        	</div>
    	</div>
    </div>
    
 

    
    <div class="slds-section slds-is-open">
        <h3 class="slds-section__title slds-theme_shade">
      		<span class="slds-truncate slds-p-horizontal_small" title="Section Title">Vehicle Details Table - 1</span>
  		</h3>
        

        <lightning:datatable data="{! v.mydata }" 
        					 columns="{! v.mycolumns }" 
        					 keyField="Id" 
        					 onrowselection="{! c.handleRowAction }"
                           />
    </div>
</aura:component>

Controller:
({
	doinit : function(component, event, helper) {
        component.set('v.mycolumns', [
            {label: 'Vehicle Name', fieldName: 'Name', type: 'text'},
            {label: 'Service Date', fieldName: 'Service_Date__c', type: 'date'}
        ]);
        
		var action = component.get('c.fetchRecords');
        action.setCallback(this, function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                var allValues = response.getReturnValue();
                console.log("allValues--->>> " + allValues);
                component.set('v.mydata', allValues);
            }
            else if(state === "ERROR") {
                var errors = response.getError();
                if(errors){
                    if(errors[0] && errors[0].message){
                        console.log("Error Message: " + errors[0].message);
                    }
                }
                else{
                    console.log("Unknown Error");
                }
            }
        });
        $A.enqueueAction(action);
	},
    
    handleRowAction : function(component, event, helper){
        var selRows = event.getParam('selectedRows');
        
        // Remove the record from the table
        var rows = component.get('v.mydata');
        for (var i = 0; i<selRows.length; i++){    
            var rowIndex = rows.indexOf(selRows[i]);
            console.log('rowIndex---->>> ' + rowIndex);
            var r=rows.splice(rowIndex, 1);   
            console.log('rrr---->>> ' + JSON.stringify(r));
            component.set('v.mydata', rows);
        }
    }
})

CSS:
.THIS {
}

.THIS .slds-section__title{
    background-color: #1589ee;
    color: white
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
sumit suwalkasumit suwalka
HI Khan,
         i have Name as auto number and two lookup field. what should i use in type in controller?
         i tried as below:-
         doinit : function(component, event, helper) {
        component.set('v.mycolumns', [
            {label: 'Name', fieldName: 'Name', type: 'Auto Number'},
            {label: 'Sister Company', fieldName: 'Sister_Company__c', type: 'id'},
            {label: 'Sister Company', fieldName: 'Sister_Company2__c', type: 'id'}

        ]);
         but its not showing anything.Any suggestions?
Khan AnasKhan Anas (Salesforce Developers) 
Hi Sumit,

For lookup fields, you have to flatten the data (server side or client side). It's a valid use case to consider.
if (state === "SUCCESS") {
                var rows = response.getReturnValue();
                for (var i = 0; i < rows.length; i++) {
                    var row = rows[i];
                    if (row.Account) row.AccountName = row.Account.Name;
                }
                component.set("v.data", rows);
                
            }

Then replace "Account.Name" with "AccountName" in the column data.
{label: 'Account Name', fieldName: 'AccountName', type: 'text'}

And for auto numbers, you can use a number as a type. Below is the sample code:

Component:
<aura:component controller="DataTableRelatedC"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    
    <!-- Three important parts of datatable is Key , data and columns
         so we need attribute for data and columns(metatadata)-->
    <!-- attributes -->
    <aura:attribute name="data" type="Object"/>
    <aura:attribute name="columns" type="List[]"/>
    
    
    <!-- handlers-->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    
    <!-- the container element determine the height of the datatable -->
    <div style="height: 300px">
        
        <lightning:datatable aura:id="opportunitydatatable"
                             
                             keyField="Id"
                             data="{!v.data}"
                             columns="{!v.columns}"/>
        
    </div>
</aura:component>

Controller:
({
    doInit : function(component, event, helper) {
        component.set('v.columns', [
            {label: 'Auto Number', fieldName: 'Auto_No__c', type: 'number', cellAttributes: {alignment: 'left'}},
            {label: 'Opportunity Name', fieldName: 'Name', editable: true, type: 'text'},
            {label: 'Account Name', fieldName: 'AccountName', type: 'text'},
            {label: 'StageName', fieldName: 'StageName', editable: true, type: 'text'},
            {label: 'CloseDate', fieldName: 'CloseDate', type: 'date'}
        ]);
        var action=component.get('c.getOpportunities');
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                var rows = response.getReturnValue();
                for (var i = 0; i < rows.length; i++) {
                    var row = rows[i];
                    if (row.Account) row.AccountName = row.Account.Name;
                }
                component.set("v.data", rows);
                
            }
        });
        $A.enqueueAction(action);
    }
})

Apex:
public class DataTableRelatedC {
    
    @AuraEnabled
    public static List<Opportunity> getOpportunities() {
        List<Opportunity> oppList=new List<Opportunity>();
        oppList=[SELECT Auto_No__c, Name, Account.Name, StageName, CloseDate FROM Opportunity];
        return oppList;
    }
}

I hope it helps you.

Regards,
Khan Anas
sumit suwalkasumit suwalka
Hi Khan Anas,
             i have implemented what you suggested ,but its not working.
             am i missing anything?
             my controller is given below:-
             ({
    doinit : function(component, event, helper) {
        component.set('v.mycolumns', [
            {label: 'Name', fieldName: 'Name', type: 'integer'},
            {label: 'Sister Company', fieldName: 'Sister_Company__c', type: 'text'},
            {label: 'Sister Company', fieldName: 'Sister_Company2__c', type: 'text'}

        ]);
        
        var action = component.get('c.fetchRecords');
        action.setCallback(this, function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                var allValues = response.getReturnValue();
                for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    if (row.Account) row.Sister_Company__c = row.Account.Name;
                }

                console.log("allValues--->>> " + allValues);
                component.set('v.mydata', allValues);
            }
            else if(state === "ERROR") {
                var errors = response.getError();
                if(errors){
                    if(errors[0] && errors[0].message){
                        console.log("Error Message: " + errors[0].message);
                    }
                }
                else{
                    console.log("Unknown Error");
                }
            }
        });
        $A.enqueueAction(action);
    },
    
    removeRow : function(component, event, helper){
        var selRows = event.getParam('selectedRows');
        
        // Remove the record from the table
        var rows = component.get('v.mydata');
        for (var i = 0; i<selRows.length; i++){    
            var rowIndex = rows.indexOf(selRows[i]);
            console.log('rowIndex---->>> ' + rowIndex);
            var r=rows.splice(rowIndex, 1);   
            console.log('rrr---->>> ' + JSON.stringify(r));
            component.set('v.mydata', rows);
        }
    }
})
Khan AnasKhan Anas (Salesforce Developers) 
Use below lines of code:
{label: 'Sister Company', fieldName: 'sc1', type: 'text'},
{label: 'Sister Company', fieldName: 'sc2', type: 'text'}
 
var allValues = response.getReturnValue();
                for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    if (row.Account) row.sc1 = row.Account.Name; // If you are using custom object then use custom object name instead of Account
                }
                console.log("allValues--->>> " + allValues);
                component.set('v.mydata', allValues);

Regards,
Khan Anas
This was selected as the best answer
sumit suwalkasumit suwalka
Hi Khan,
when i tried as you said its not showing anything in Sister_Company__c
here my object is FBG_Family__c and Sister_Company__c ,Sister_Company2__c are field on FBG_Family__c which are lookup of Account.
i tried like this :-
 var allValues = response.getReturnValue();
                for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    if (row.FBG_Family__c) row.Sister_Company__c = row.Sister_Company__c.Name;
                }
                console.log("allValues--->>> " + allValues);
                component.set('v.mydata', allValues);
is it right?
sumit suwalkasumit suwalka
Hi khan ,
thanks for the help.
found the solution:-
 var allValues = response.getReturnValue();
                for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    row.s1 = row.Sister_Company__r.Name;
                }
                 for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    row.s2 = row.Sister_Company2__r.Name;
                }