[SalesForce] Dynamically add and remove rows in lightning

I have to dynamically add and delete records in my lightning page.

I have done with adding the rows but I am not getting how i will remove the records. Rather I am not understanding how I will get the record that i have to delete as an parameter.

App

<aura:application >
<c:AddDeleteMapping>
</aura:application>

Component

<aura:component controller="AddMappingController">  
<aura:attribute name="wrappers" type="OpportunityRollOverStageMapping[]"  />
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<aura:registerEvent name="deleteExpenseItem" type="c:deleteExpenseItem"/>

<table>
    <tr>
        <th class="head">Count</th>
        <th class="head">From Stage</th>
        <th class="head">To Stage</th>
        <th class="head"></th>
    </tr>
    <aura:iteration items="{!v.wrappers}" var="wrap">
        <tr>
            <td class="cell">
                <ui:outputText value="{!wrap.count}" />
            </td>
            <td class="cell">
                <ui:outputText value="{!wrap.fromStage}" />
            </td>
            <td class="cell">
                <ui:outputText value="{!wrap.toStage}" />
            </td>
            <td class="cell">
                <ui:button label="Delete" press="{!c.deleteMapping}"/>
            </td>
        </tr>
    </aura:iteration>
</table>
<button onclick="{!c.addMapping}">Add Mapping</button>

lightning Controller

({

doInit : function(component, event, helper) {   
    helper.GetStageMapping(component);

},
addMapping : function(component, event, helper){
    helper.AddStageMapping(component); 
},

deleteMapping : function(component, event, helper){
}})

Helper

({

GetStageMapping : function(component){
    var action = component.get("c.getFromStageAndToStages");
    var responses ='';
    action.setCallback(this,function(response){
        responses = response.getReturnValue();
        var wrappers=new Array();
        if(component.isValid()){
            var wrappers=new Array(); 
            for (var idx=0; idx<responses.length; idx++) {
                var wrapper = { 'count' : responses[idx].count,
                               'fromStage' : responses[idx].fromStage,
                               'toStage' : responses[idx].toStage
                              }; 
                wrappers.push(wrapper);

            }
            component.set("v.wrappers",wrappers );
        }

    });
    $A.enqueueAction(action);
},    

AddStageMapping:function(component){
    var action = component.get("c.getAddedStageAndToStages");
    var responses ='';
    var wrappers=component.get('v.wrappers');
    alert('wRAPPERS: '+ wrappers);
    var mappRecords = new Array(); 
    for (var idx=0; idx<wrappers.length; idx++) {
        mappRecords.push(wrappers[idx]);
    }
    var ListJSON=JSON.stringify(mappRecords);
    alert(ListJSON);
    action.setParams({
        OpportunityRollOverStageMapping : ListJSON
    });

    action.setCallback(this,function(response){
        responses = response.getReturnValue();
        var wrappers=new Array();
        if(component.isValid()){
            var wrappers=new Array(); 
            for (var idx=0; idx<responses.length; idx++) {
                var wrapper = { 'count' : responses[idx].count,
                               'fromStage' : responses[idx].fromStage,
                               'toStage' : responses[idx].toStage
                              }; 
                wrappers.push(wrapper);

            }
            component.set("v.wrappers",wrappers );
        }

    });
    $A.enqueueAction(action);
},    

DeleteMapping : function(component, expense, callback) {

}

})

Apex Controller

public class AddMappingController {

public static List<OpportunityRollOverStageMapping> listStageMappings;
public AddMappingController (){
    listStageMappings = new List<OpportunityRollOverStageMapping>();
}

@AuraEnabled
public static List<OpportunityRollOverStageMapping> getFromStageAndToStages(){
    listStageMappings = new List<OpportunityRollOverStageMapping>();
    List<OpportunityRollOverStageMapping> wcList = new List<OpportunityRollOverStageMapping>();
    for(integer i =0 ; i< 2; i++){
        OpportunityRollOverStageMapping opportunityRollOverStageMap= new OpportunityRollOverStageMapping();
        opportunityRollOverStageMap.count = i;
        opportunityRollOverStageMap.fromStage= 'str'+i;
        opportunityRollOverStageMap.toStage= 'str'+i;
        listStageMappings.add(opportunityRollOverStageMap);
        wcList.add(opportunityRollOverStageMap);
    }
    return wcList;
}


@AuraEnabled
public static List<OpportunityRollOverStageMapping> getAddedStageAndToStages(string OpportunityRollOverStageMapping){
    Type stageMappingType = Type.forName('List<OpportunityRollOverStageMapping>');
    List<OpportunityRollOverStageMapping> parameterList = (List<OpportunityRollOverStageMapping>) JSON.deserialize(OpportunityRollOverStageMapping, stageMappingType);

    List<OpportunityRollOverStageMapping> wcList =new List<OpportunityRollOverStageMapping>();
    wcList.addAll(parameterList);

    OpportunityRollOverStageMapping opportunityRollOverStageMap= new OpportunityRollOverStageMapping();
    opportunityRollOverStageMap.count = wcList.size();
    opportunityRollOverStageMap.fromStage= 'str'+wcList.size();
    opportunityRollOverStageMap.toStage= 'str'+wcList.size();
    wcList.add(opportunityRollOverStageMap);
    return wcList;
}

@AuraEnabled
public static string  deleteExpenseItem(string OpportunityRollOverStageMapping) {
    return 'srk';
}}

Add the element as new row is done. But how will i delete the specific selected row from the list?

enter image description here

Best Answer

I have done a simple component which display contacts list which involves two components

1.ContactList - Parent (Fetches the contact details)

2.ContactListItem - Child (Display individual contact detail)

Component Level Event is used to carry the contact from ContactListItem to ContactList which holds the source contact array where contact removal is done.

ContactList.cmp

<aura:component access="public" controller="ContactController">
    <aura:attribute name="contacts" type="Contact[]" access="private"/>
    <aura:handler name="init" action="{!c.doInit}" value="{!this}" />
    <aura:handler name="deleteContact" event="c:deleteContactEvt" action="{!c.removeContact}" />
    <table class="borderCls">
        <tr>
            <th class="borderCls">Name</th> 
            <th class="borderCls">Phone</th>
        </tr>   
        <aura:iteration items="{!v.contacts}" var="contact">
            <c:ContactListItem contactRec="{!contact}"/>
        </aura:iteration>
    </table>
    <button onclick="{!c.addContact}">Add Contact</button>
</aura:component>

ContactListController.js

({
    doInit : function(component, event, helper) {
        var action = component.get("c.getContacts");
        action.setCallback(this, function(data) {
            console.log(data.getReturnValue());
            component.set("v.contacts", data.getReturnValue());
        });
        $A.enqueueAction(action);
    }
    ,
    addContact : function(component, event, helper){
       var contacts = component.get("v.contacts");
        var len = contacts.length;
        contacts.push({
            'Name':'Test Contact - '+len,
            'Phone':'123'+len
            'sobjectType':'contact'
        });
        component.set("v.contacts",contacts);
    }
    ,
    removeContact : function(component, event, helper){
       var selCont = event.getParam("selectedContact");
       var contacts = component.get("v.contacts")
       var index = contacts.indexOf(selCont);
       if (index > -1) {
            contacts.splice(index, 1);
       }
       component.set("v.contacts",contacts);
    }
})

ContactListItem.cmp

<aura:component >
    <aura:attribute name="contactRec" type="Contact" access="public"/>
    <aura:registerEvent name="deleteContact" type="c:deleteContactEvt"/>
    <tr > 
        <td class="borderCls" >{!v.contactRec.Name}</td> 
        <td class="borderCls" >{!v.contactRec.Phone}</td>
        <td> <ui:button label="Delete" press="{!c.deleteContact}"/></td>
    </tr>
</aura:component>

ContactListItemController.js

({
    deleteContact : function(component, event, helper) {
        var event = component.getEvent("deleteContact");
        event.setParams({
            'selectedContact':component.get("v.contactRec")
        });
        event.fire();
    }
})

deleteContactEvt.evt (Component Level Event)

<aura:event type="COMPONENT" description="Delete Contact Event">
    <aura:attribute name="selectedContact" type="Contact"/>
</aura:event>

ApexController

public class ContactController {
    @AuraEnabled
    public static List<Contact> getContacts() {
        return [Select Id, Name, Birthdate, AccountId, Account.Name, Email, Title, Phone 
                From Contact order by LastModifiedDate desc
                limit 10];
    }
}

I Hope this helps

Related Topic