TransWikia.com

Lightning DataTable, adding duplicates and deleting the wrong row

Salesforce Asked by Daniel Bauer on December 12, 2020

I have 2 lightning data tables, table A is populated by all active products, table b is populated with the selected rows from the first. table a is filterable, and I’d like to persist the selections until the user clicks a button to go to table b. Its adding duplicated, and also when the user clicks delete, its deleting the last row not the row the button was clicked on.

.cmp

<aura:component Controller = "ProductQuickAddController" implements="force:hasSObjectName,force:hasRecordId,flexipage:availableForAllPageTypes,force:appHostable,force:lightningQuickAction" access="global">
    <!-- attributes -->
    <aura:attribute name="productList" type="Object" />
    <aura:attribute name="productCols" type="List" />
    <aura:attribute name="filteredProducts" type="List" />
  
    
    <aura:attribute name="selectedRows" type="List"/>
    <aura:attribute name="PersistRows" type="List"/>
    <aura:attribute name="selection" type="List" />
    <aura:attribute name="recordId" type="String"/>
    
    <aura:attribute name="searchText" type="String" />
    <ltng:require styles="{!$Resource.ModalCSS}"/>
    
    <aura:attribute name="addProductsCols" type="List" />
    <aura:attribute name="saveDraftValues" type="Object"/>
    
     <!-- handlersselectedRows = "{!v.PersistRows}"-->
   <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
   
    <div style="height: 90%; padding: 10px;" aura:id="Products">
        <lightning:layout verticalAlign="end">
    <lightning:layoutItem flexibility="grow">
        <span onkeypress="{!c.keyCheck}">
            <lightning:input label="Search" type="search" value="{!v.searchText}" name="search"/><br/>
            Press Enter to filter results.
           
        </span>
    </lightning:layoutItem>
</lightning:layout>
        
      
        <center>
            <div style="height: 500px; padding: 10px;">
        <lightning:datatable
            aura:id="tblProducts"
            columns="{!v.productCols}"
            data="{!v.filteredProducts}"           
            keyField="Id"
            
            onrowselection="{!c.getSelected}"/>
                
        </div>
            </center> 
        <div id="controls" style="float:right; padding: 10px;">
            <lightning:button variant="brand" label="Set Prices" title="Set Prices" onclick="{!c.selectedProducts }" />
    </div>
    </div>
   
    <div style="height: 100%; padding: 10px;" aura:id="addProducts">
    <lightning:datatable
            aura:id="SelectedProducts"
            columns="{!v.addProductsCols}"
            data="{!v.selection}"           
            keyField="Id"
            hideCheckboxColumn="true"
            onrowaction="{!c.handleRowAction}"
            onsave="{!c.handleSave}"/>
        
        <br/>
        <div id="backbutton" style="float: right">
            <lightning:button variant="brand" label="Add More Products" title="back" onclick="{!c.moreProducts }" />
        </div>
    </div>
    
    
</aura:component>

controller.js

({
    doInit : function(component, event, helper) {
        
        component.set('v.productCols', [
            
            //{label: ' ', type: 'button', initialWidth: 85, typeAttributes: { label: '', iconName: 'utility:add', name: 'add', title: 'Add Product', variant: 'brand'}},
            {label: 'Name', initialWidth: 200, fieldName: 'Name', type: 'text'},
            {label: 'Code', initialWidth: 85, fieldName: 'ProductCode', type: 'text'},
            {label: 'Family', initialWidth: 200, fieldName: 'Family', type: 'text'},
            {label: 'Description', fieldName: 'Description', type: 'text'}
        
        ]);
        
        
      
        component.set('v.addProductsCols', [
            
            {label: 'Name', fieldName: 'Name', type: 'text'},
            {label: 'Description', fieldName: 'Description', type: 'text', editable: true}, 
            {label: 'Sales Price', fieldName: 'UnitPrice', type: 'currency', typeAttributes: { currencyCode: 'USD'}, editable: true, typeAttributes: { required: true }}, 
            {label: 'Quantity', fieldName: 'Quantity', type: 'number', editable: true, typeAttributes: { required: true }},
            {label: ' ', type: 'button', initialWidth: 95, typeAttributes: { label: 'Delete', name: 'delete', title: 'Remove Product', variant: 'brand'}}
        
        ]);

        helper.fetchProducts(component, event);
        
         $A.util.removeClass(component.find("Products"), "slds-hide");
        $A.util.addClass(component.find("addProducts"), "slds-hide");
        
    }, 
    
    filter: function(component, event, helper) {
             
        helper.getSearchResults(component, event);
    }, 
    getSelected: function(component, event, helper) {
                
        var selectedRows = event.getParam('selectedRows');  
        var allSelectedRows = component.get("v.selection");
        
        var row = event.getParam('row');
        var rows = component.get('v.PersistRows');
        
        var rowIndex = rows.indexOf(row);

        rows.push(row);
        component.set('v.PersistRows', rows);
        
        selectedRows.forEach(function(row) {
                allSelectedRows.push(row);
            
            });
        component.find("tblProducts");
        component.set("v.selection", allSelectedRows);
        
        
       
    
    },    
    selectedProducts: function(component, event, helper) {
        
        $A.util.removeClass(component.find("addProducts"), "slds-hide");
        $A.util.addClass(component.find("Products"), "slds-hide");        
       
        
    },    
    moreProducts: function(component, event, helper) {
        
        $A.util.removeClass(component.find("Products"), "slds-hide");
        $A.util.addClass(component.find("addProducts"), "slds-hide");        
       
        
    },  
    handleSave : function(component, event, helper) {
        component.set('v.saveDraftValues', event.getParam('draftValues'));
        
        var drafts = event.getParam('draftValues');        
        
              
        helper.savelItems(component,event);
    }, 
    handleRowAction: function (component, event, helper) {
        
        var row = event.getParam('row');

        helper.removeProd(component, row);
       
        
    },
    keyCheck : function(component, event, helper){
        if(event.which == 13){
             helper.getSearchResults(component, event);
        }
        
    }
    
    
})

helper.js

({
    fetchProducts : function(component, event) {
        
          var action = component.get('c.getProducts')
        
          var self = this;
               
                 
          action.setCallback(this, function(response) {
            component.set('v.productList', response.getReturnValue());
            component.set('v.filteredProducts', response.getReturnValue());
        } );
        $A.enqueueAction(action);
        
    }, 
    searchEvents: function(component, event, helper) {
      console.log(event.getParams().keyCode);
      if(event.getParams().keyCode == 13){
        alert('Enter key pressed');
      }
   },
    getSearchResults : function(component, event) {
     
        var strSearch = component.get("v.searchText")
        
        var action = component.get('c.getResults')
        
        var self = this;
          action.setParams({"searchStr":strSearch});
                 
          action.setCallback(this, function(response) {
            component.set('v.productList', response.getReturnValue());
            component.set('v.filteredProducts', response.getReturnValue());            
        } );
        $A.enqueueAction(action);
        
        
    },     
    savelItems : function(component, event){
        
        var record = component.get("v.recordId");        
        var draftItems = component.get("v.saveDraftValues"); 
        
        var items = JSON.stringify(draftItems); 
        
        
        var action = component.get('c.insertLineItems')
        
        var self = this;
        action.setParams({"lItems":items, "objectID":record});
                 
        action.setCallback(this, function(response) {
            
        var state = response.getState();
            console.log(state);
            if (state === "SUCCESS") {
           
                console.log("From server: Success");   
                alert("Item(s) Added to Quote.");
                window.location.reload()

            }
            else if (state === "ERROR") {
                 
                var errorMsg = response.getError();
                let toastParams = {
                    title: "!Error!",
                        message: "Please contact system administrator.", // Default error message
                        type: "error"
                        };
                let toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams(toastParams);
                toastEvent.fire();
      
            }
        });
        $A.enqueueAction(action);
    }, 
    removeProd : function(component, event, row){
        
        var rows = component.get('v.selection');
        var rowIndex = rows.indexOf(row);

        rows.splice(rowIndex, 1);
        component.set('v.selection', rows);
    }
    
})

One Answer

Here is the corrected Code:

Remove Duplicates:

 //check for duplicates and remove
        allSelectedRows = allSelectedRows.filter( function( item, index, inputArray ) {
           return inputArray.indexOf(item) == index;
        });    
        

Delete correct Row:

 removeProd : function(component, event){
        
        var row = event.getParam('row');
        var rows = component.get('v.selection');
        var rowIndex = rows.indexOf(row);

        rows.splice(rowIndex, 1);
        component.set('v.selection', rows);
    }

Correct answer by Daniel Bauer on December 12, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP