2

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

  • Adding New Row can be done in Lightning component itself unless and until you don't need to fetch any data from org.Please see my answer below it might help you. – Praveen May 12 '16 at 19:16
  • how to do this in LWC? – compski Nov 8 at 5:59
5

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

  • I have used this code, but however when I add new contacts and try to send it to apex controller method. It gives this error Unable to read SObject Can you please let me know how to send the newly added data to apex controller method. – Mustafa Jhabuawala Nov 19 '16 at 14:18
  • @MustafaJ Added sobjectType to the object while pushing it to contacts array.See the updated answer. – Praveen Nov 21 '16 at 17:46
  • @Praveen actually i am new to lightning but when i tried to save component ContactList.cmp.I got an error like No ATTRIBUTE named contactRec found: Source – Pavan tej Jun 18 '17 at 18:35
  • @Pavantej setting access="private" will not expose attribute to its parent component. I've updated the answer please check it out. – Praveen Jun 18 '17 at 19:20
  • Thanks @praveen But i need this component in account page for create contacts directly.But When i try to display in account page it's saying component doesn't have properties.Is this component is works for my requirement. – Pavan tej Jun 19 '17 at 7:07
1

I had a small problem with the solution, the only change that I've made was that I changed var event in ContactListItemController.js to some other name: event1

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

Now it works perfectly, hope this helps if anyone will have problem like me :)

problem:

Uncaught [Cannot read property '$setParams$' of undefined Events...

0

In your case you didn't add deletemapping java script code.Here you no need to call any server methods.why beacuse javascript splice functionality take care that one.One thing you have to do design one more component.Using the event you have to communicate with that component thats better approach otherwise after clicking add row the value may vanish[earlier your added values].

If it helps means please make it as best answer.It helps for other people for finding same answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.