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
SHAIK MOULALI369SHAIK MOULALI369 

Adding or deleting rows in custom object in lightning component

Adding or deleting rows on custom object in lightning component.
while executing helper methode "action.setParams();" and "action.setCallback();" are not working properly.

Component Code : 
<aura:component controller="Schools_Buddy_Student" Implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,
                                                     force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global">     
    <aura:attribute name="StudentList" type="Student__c[]"/>
    <aura:attribute name="Gender" type="String[]" default=" , Male, Female, Transgender"/>
    
    <div class="slds-m-around--xx-large">
        <div class="slds-float_right slds-p-bottom_small">
            <h1 class="slds-page-header__title">Add Row 
                <lightning:buttonIcon iconName="utility:add"  size="large" variant="bare" alternativeText="Add" onclick="{!c.addRow}"/>
            </h1>
        </div>
        <div class="container-fluid">        
            <table class="slds-table slds-table_bordered slds-table_cell-buffer"> 
                <thead>
                    <tr class="slds-text-title_caps">
                        <th scope="col">
                            <div class="slds-truncate">#</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Student Name">Student Name</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Student Email">Email ID</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Phone">Phone Number</div>
                        </th>
                        <th scope="col">
                            <div class="slds-truncate" title="Action">Action</div>
                        </th>
                    </tr>
                </thead>   
                <tbody>      
                    <aura:iteration items="{!v.StudentList}" var="acc" indexVar="index">
                        <tr>
                            <td> 
                                {!index + 1}
                            </td>
                            <td>
                                <lightning:input name="accName" type="text" required="true" maxlength="50" label="Student Name" value="{!acc.Name}" />
                            </td>
                            <td>
                              	<lightning:input name="" type="text"  maxlength="80" label="Email ID" value="{!acc.Email_ID__c}" />
                            </td>
                            <td>
                                <lightning:input name="accPhone" type="phone" maxlength="50" label="Phone" value="{!acc.Phone__c}" />
                            </td>
                            <td>
                                <a onclick="{!c.removeRow}" data-record="{!index}">
                                    <lightning:icon iconName="utility:delete" size="small" alternativeText="Delete"/>
                                    <span class="slds-assistive-text">Delete</span>
                                </a>
                            </td> 
                        </tr>
                    </aura:iteration>
                </tbody>
            </table>
            <div class="slds-align_absolute-center slds-p-top_small">
                <lightning:button variant="brand" label="Submit" title="Brand action" onclick="{!c.save}" />
            </div>
        </div>
    </div>
</aura:component>
Controller Code :
({
    addRow: function(component, event, helper) {
        helper.addAccountRecord(component, event);
       
    },     
    removeRow: function(component, event, helper) {
        var StudentList = component.get("v.StudentList");
        var selectedItem = event.currentTarget;
        var index = selectedItem.dataset.record;
        StudentList.splice(index, 1);
        component.set("v.StudentList", StudentList);
    },     
    save: function(component, event, helper) {
        if (helper.validateAccountList(component, event)) {
            helper.saveAccountList(component, event);
            alert('SaveCmp');
        }
    },
})
Helper methode : 
({
    addAccountRecord: function(component, event) {
        var StudentList = component.get("v.StudentList");
        StudentList.push({
            'sobjectType': 'Student__c',
            'Name': '',
            'Email_ID__c': '',
            'Phone__c': ''
        });
        component.set("v.StudentList", StudentList);
    },     
    validateAccountList: function(component, event) {
        var isValid = true;
        var StudentList = component.get("v.StudentList");
        for (var i = 0; i < StudentList.length; i++) {
            if (StudentList[i].Name == '') {
                isValid = false;
                alert('Account Name cannot be blank on row number ' + (i + 1));
            }
        }
        return isValid;
    },     
    saveAccountList: function(component, event, helper) {
        alert('before calling saveStudent');
        var action = component.get("c.saveStudents");
        alert('aftr calling saveStudent');
        action.setParams({
            "stList": component.get("v.StudentList")
        });
        alert('After setParams');
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.StudentList", []);
                alert('Account records saved successfully');
            }
            else if (state === "INCOMPLETE") {
                alert('Incomplete Action');
            }
            else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + 
                                 errors[0].message);
                        alert('errors[0].message : '+errors[0].message);
                    }
                } else {
                    alert("Unknown error");
                }
            }
        }); 
        $A.enqueueAction(action);
    },
})
Server side Controller Code :
public with sharing class Schools_Buddy_Student {     
    
    @AuraEnabled
    public static void saveStudents(List<Student__c> stList){
        Insert stList;
    }
}
Image of Adding multiple student data in rows:

User-added image


Kindly suggest how to resolve this Issue.
 
ANUTEJANUTEJ (Salesforce Developers) 
Hi Shaik,

>> https://www.greytrix.com/blogs/salesforce/2021/03/24/add-delete-row-dynamically-in-salesforce-lightning/

The above link has a similar implementation can you try checking it once?

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.  

Thanks.
ravi soniravi soni
hi Shaik,
I have Checked your Code and Tested in my org but i faced some error for inserting records but now it's working fine.
you will have to do some small changes in your helper class.
1. Add  this line  alert(state); below  var state = response.getState(); so that you can figur out that your code is generating error or success. 
2.  alert('errors : ' + JSON.stringify(errors)); add this line start of this method  else if (state === "ERROR") {

you can replace the method with your method.
saveAccountList: function(component, event, helper) {
        alert('before calling saveStudent');
        var action = component.get("c.saveStudents");
        alert('aftr calling saveStudent');
        console.log('studentList : ' + JSON.stringify(component.get("v.StudentList")));
        action.setParams({
            "stList": component.get("v.StudentList")
        });
        alert('After setParams');
        action.setCallback(this, function(response) {
            var state = response.getState();
            alert(state);
            if (state === "SUCCESS") {
                component.set("v.StudentList", []);
                alert('Account records saved successfully');
            }
            else if (state === "INCOMPLETE") {
                alert('Incomplete Action');
            }
            else if (state === "ERROR") {
                var errors = response.getError();
               alert('errors : ' + JSON.stringify(errors));
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + 
                                 errors[0].message);
                        alert('errors[0].message : '+errors[0].message);
                    }
                } else {
                    alert("Unknown error");
                }
            }
        }); 
        $A.enqueueAction(action);
    },

your complete code is fine but I think it is generating some validation or required field errors. once you have to check your apex debug log.
Let me know if above info is useful for you and marking it as best Answer.
Thank you