Editing row, Saving row and Removing rows Dynamically in Lightning component Salesforce | how to edit/save row dynamically in Salesforce lightning component

3,583 views


Hey guys, In this post we are going to learn about that how to edit row, saving row or removing row dynamically in Salesforce lightning component.

In this example we will customize the same component and achieve to the editing row, saving row and removing rows functionality of dynamically on Custom sObject by help of wrapper apex class and JavaScript Controller in lightning component.

We do not allow to Delete or Edit multiple rows at a same time. First you will need to cancel of the current rows than after you will be able to delete or edit of another rows.

Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!

 

 

Files we used in this post example:-

wrapperClassCustomObjCmp.cmp Lightning Component It is used for display the Input filed of Name, Address, Email, and Button Icon of Edit, Delete, Cancel and Save on the Table.
wrapperClassCustomObjCmpConroller.js JavaScript Controller File It is used for Edit, Save, Cancel and Delete functionality and this function communicate to server side apex method.
wrapperClassCustomObjCmpHelper.js JavaScript Helper File It is used for refresh the page after delete or Save the record.
wrapperCustomObjCtrCmp.apxc Apex Class Controller It is used for delete and save record from database server

Custom Object:- NewStudent__c

Custom Object Fields:-

Email__c

Address__c

 

Custom Object and their fields Custom object like database and custom fields are columns of data table. We customized the record of both fields by using the apex class method.

Final Output

Editing row, Saving row, Deleting row in lightning component -- w3web.net

 

You can download file directly from github by Click Here.

 

Other related post that would you like to learn in Salesforce

 

Note:- Custom sObject >> NewStudent__c

You need to change custom sObject name and there fields name with your custom sObject.

Step 1:- Create Lightning Component : wrapperClassCustomObjCmp.cmp

Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
 
 

From Developer Console >> File >> New >> Lightning Component

wrapperClassCustomObjCmp.cmp [Lightning Component File]

  1.    <aura:component controller="wrapperCustomObjCtrCmp" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction,lightning:isUrlAddressable" access="global" >
  2.  
  3.     <aura:attribute name="wrapListItems" type="NewStudent__c[]"/>
  4.     <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
  5.     <aura:attribute name="recSelectId" type="String" default=""/>
  6.  
  7.     <div class="slds slds-p-horizontal--medium">
  8.         <table class="slds-table slds-table--bordered slds-table--col-bordered" style="border-collapse:collapse;">
  9.             <thead> 
  10.                 <tr>
  11.                     <th>Student Name</th>
  12.                     <th>Address</th>
  13.                     <th>Email</th>                     
  14.                     <th></th>
  15.                 </tr>
  16.             </thead>
  17.             <tbody>
  18.                 <aura:iteration items="{!v.wrapListItems}" var="wrapVar" indexVar="index">
  19.                     <tr id="{!wrapVar.recStudentId}">
  20.                         <aura:if isTrue="{!wrapVar.editMode}"> 
  21.                             <td><ui:inputText aura:id="studentName"  value="{!wrapVar.studentName}"/></td>
  22.                             <aura:set attribute="else">
  23.                                 <td>{!wrapVar.studentName}</td>
  24.                             </aura:set>
  25.                         </aura:if>
  26.  
  27.                         <aura:if isTrue="{!wrapVar.editMode}"> 
  28.                             <td><ui:inputTextArea aura:id="addressId" value="{!wrapVar.studentAddress}" rows="2"/></td>
  29.                             <aura:set attribute="else">
  30.                                 <td>{!wrapVar.studentAddress}</td>
  31.                             </aura:set>
  32.                         </aura:if>
  33.  
  34.                          <aura:if isTrue="{!wrapVar.editMode}"> 
  35.                             <td><ui:inputEmail aura:id="emailId" value="{!wrapVar.studentEmail}"/></td>
  36.                             <aura:set attribute="else">
  37.                                 <td>{!wrapVar.studentEmail}</td>
  38.                             </aura:set>
  39.                         </aura:if>
  40.  
  41.                         <aura:if isTrue="{!wrapVar.editMode}">  
  42.                             <td>                                
  43.                                 <a href="javascript:void(0);"><span class="saveSpan slds-m-left--small" title="Save" onclick="{!c.saveEditedTalent}" 
  44.                                                                     data-sfid="{!wrapVar.recStudentId}"
  45.                                                                     id="{!wrapVar.recStudentId}"
  46.                                                                     data-index="{!index}"></span></a>
  47.  
  48.                                 <a class="slds-text-color--error" href="javascript:void(0);"><span style="font-size:18px; font-weight:bold;" class="slds-m-left--small" title="Cancel" onclick="{!c.cancelEdit}" 
  49.                                                                     data-sfid=""
  50.                                                                     data-index="{!index}">X</span></a>
  51.  
  52.                             </td>
  53.                             <aura:set attribute="else">
  54.                                 <td> 
  55.                                     <a href="javascript:void(0);"><span class="editSpan slds-m-left--small" title="Edit" onclick="{!c.editTalent}" 
  56.                                                                         data-sfid="{!wrapVar.recStudentId}"
  57.                                                                         id="{!wrapVar.recStudentId}"
  58.                                                                         data-index="{!index}"></span></a>
  59.  
  60.                                     <a href="javascript:void(0);"><span class="delSpan slds-m-left--small" title="Delete" onclick="{!c.deleteRowId}" 
  61.                                                                         data-sfid="{!wrapVar.recStudentId}"
  62.                                                                         data-index="{!index}"></span></a>
  63.  
  64.                                 </td>  
  65.                             </aura:set>
  66.                         </aura:if>
  67.  
  68.                     </tr>
  69.                 </aura:iteration>
  70.             </tbody>
  71.         </table>
  72.  
  73. <br/><br/>
  74.    <!--Start RelatedTopics Section-->
  75. <div style="border:1px #ddd solid; padding:10px; background:#eee; margin:40px 0;">
  76.  
  77.             <p data-aura-rendered-by="435:0"><img src="https://www.w3web.net/wp-content/uploads/2021/05/thumbsUpLike.png" width="25" height="25" style="vertical-align:top; margin-right:10px;" data-aura-rendered-by="436:0"><strong data-aura-rendered-by="437:0"><span style="font-size:16px; font-style:italic; display:inline-block; margin-right:5px;">Don't forget to check out:-</span><a href="https://www.w3web.net/" target="_blank" rel="noopener noreferrer" style="text-decoration:none;" data-aura-rendered-by="440:0">An easy way to learn step-by-step online free Salesforce tutorial, To know more Click  <span style="color:#ff8000; font-size:18px;" data-aura-rendered-by="442:0">Here..</span></a></strong></p>
  78.  
  79.             <br/><br/>
  80.             <p data-aura-rendered-by="435:0"><img src="https://www.w3web.net/wp-content/uploads/2021/07/tickMarkIcon.png" width="25" height="25" style="vertical-align:top; margin-right:10px;" data-aura-rendered-by="436:0"><strong data-aura-rendered-by="437:0"><span style="font-size:17px; font-style:italic; display:inline-block; margin-right:5px; color:rgb(255 128 0);">You May Also Like →</span> </strong></p>
  81.             <div style="display:block; overflow:hidden;"> 
  82.                 <div style="width: 50%; float:left; display:inline-block">
  83.                     <ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;"> 
  84.                         <li><a href="https://www.w3web.net/lwc-get-set-lightning-checkbox-value/" target="_blank" rel="noopener noreferrer">How to get selected checkbox value in lwc</a></li>
  85.                         <li><a href="https://www.w3web.net/display-account-related-contacts-in-lwc/" target="_blank" rel="noopener noreferrer">how to display account related contacts based on AccountId in lwc</a></li>
  86.                         <li><a href="https://www.w3web.net/create-lightning-datatable-row-actions-in-lwc/" target="_blank" rel="noopener noreferrer">how to create lightning datatable row actions in lwc</a></li>
  87.                         <li><a href="https://www.w3web.net/if-and-else-condition-in-lwc/" target="_blank" rel="noopener noreferrer">how to use if and else condition in lwc</a></li>
  88.                         <li><a href="https://www.w3web.net/get-selected-radio-button-value-and-checked-default-in-lwc/" target="_blank" rel="noopener noreferrer">how to display selected radio button value in lwc</a></li>
  89.                     </ul>
  90.             </div>
  91.  
  92.             <div style="width: 50%; float:left; display:inline-block">
  93.                     <ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;"> 
  94.                         <li><a href="https://www.w3web.net/display-account-related-contacts-lwc/" target="_blank" rel="noopener noreferrer">display account related contacts based on account name in lwc</a></li>
  95.                         <li><a href="https://www.w3web.net/create-lightning-datatable-row-actions-in-lwc/" target="_blank" rel="noopener noreferrer">how to insert a record of account Using apex class in LWC</a></li>
  96.                         <li><a href="https://www.w3web.net/fetch-picklist-values-dynamic-in-lwc/" target="_blank" rel="noopener noreferrer">how to get picklist values dynamically in lwc</a></li>
  97.                         <li><a href="https://www.w3web.net/edit-save-and-remove-rows-dynamically-in-lightning-component/" target="_blank" rel="noopener noreferrer">how to edit/save row dynamically in lightning component</a></li>
  98.                         <li><a href="https://www.w3web.net/update-parent-object-from-child/" target="_blank" rel="noopener noreferrer">update parent field from child using apex trigger</a></li>
  99.                     </ul>
  100.                 </div>
  101.                <div style="clear:both;"></div> 
  102.                <br/>
  103.                 <div class="youtubeIcon">
  104.                     <a href="https://www.youtube.com/channel/UCW62gTen2zniILj9xE6LmOg" target="_blank" rel="noopener noreferrer"><img src="https://www.w3web.net/wp-content/uploads/2021/11/youtubeIcon.png" width="25" height="25" style="vertical-align:top; margin-right:10px;"/> <strong>TechW3web:-</strong> To know more, Use this <span style="color: #ff8000; font-weight: bold;">Link</span> </a>
  105.                 </div>
  106.     </div>
  107.  
  108. </div>
  109.  
  110.   <!--End RelatedTopics Section-->
  111.  
  112.  
  113.     </div>
  114.  
  115. </aura:component>

Step 2:- Create Lightning Component : wrapperClassCustomObjCmpConroller.js

From Developer Console >> File >> New >> Lightning Component >> JavaScript Controller

wrapperClassCustomObjCmpConroller.js [JavaScript Controller]

  1.    ({
  2. 	doInit : function(component, event, helper) {    
  3.  
  4. 	  var action = component.get("c.appCustomWrapListMthd");
  5.         action.setCallback(this, function(response){
  6.             var state = response.getState();            
  7.             if(state=='SUCCESS'){
  8.                 var result = response.getReturnValue();              
  9.                 component.set('v.wrapListItems',result);
  10.             }
  11.         });
  12.         $A.enqueueAction(action);
  13. 	},
  14.  
  15.     editTalent : function( component, event, helper ) {
  16.         var index = event.target.dataset.index;
  17.         var thisObjId = event.target.dataset.sfid;
  18.          var thisId = event.target.id;
  19.         var wrapListItems = component.get( "v.wrapListItems" );        
  20.         component.set('v.recSelectId',thisId);
  21.         for ( var i = 0; i < wrapListItems.length; i++ ) {
  22.             if(wrapListItems[i].editMode == true){
  23.                 var eventToast = $A.get("e.force:showToast");
  24.                 eventToast.setParams({
  25.                     "title":'Error',
  26.                     "type":'error',
  27.                     "message":'You can edit only one record at a time.'
  28.                 });
  29.                 eventToast.fire();
  30.                 return false;
  31.             }
  32.             wrapListItems[i].editMode = false;
  33.         }
  34.         wrapListItems[index].editMode = true;
  35.         component.set( "v.wrapListItems", wrapListItems );        
  36.     },
  37.  
  38.     cancelEdit : function(component, event, helper) {        
  39.         var index = event.target.dataset.index;
  40.         var wrapListItems = component.get( "v.wrapListItems" );
  41.         wrapListItems[index].editMode = false;
  42.         component.set( "v.wrapListItems", wrapListItems );         
  43.          helper.refreshView(component);
  44.     },
  45.  
  46.     saveEditedTalent:function(component, event, helper){
  47.         var action = component.get("c.saveEdited");
  48.         var studentVal = component.find('studentName').get('v.value');
  49.         var addressId = component.find('addressId').get('v.value');
  50.         var emailId = component.find('emailId').get('v.value');
  51.  
  52.         var recIdName = component.get('v.recSelectId');        
  53.         action.setParams({"editName":studentVal, "editAddress":addressId, "editEmail":emailId, "recId":recIdName});
  54.         action.setCallback(this, function(response){
  55.             var state = response.getState();
  56.  
  57.             if(state == "SUCCESS"){
  58.                 var result = response.getReturnValue();
  59.                 var index = event.target.dataset.index;
  60.                  helper.refreshView(component);
  61.                 component.set('v.recSelectId',null);
  62.                 var eventToast = $A.get("e.force:showToast");
  63.                 eventToast.setParams({
  64.                     "title":'Success',
  65.                     "type":'success',
  66.                     "message":'Record updated successfully.'
  67.                    });
  68.                  eventToast.fire();                 
  69.             }
  70.         });
  71.         $A.enqueueAction(action);
  72.  
  73.     },
  74.  
  75.     deleteRowId:function(component,event,helper){
  76.         var sfid = event.target.dataset.sfid;        
  77.         var action =component.get('c.delectRecId');       
  78.         action.setParams({'delRecId':sfid});
  79.         action.setCallback(this, function(response){
  80.             var state = response.getState();
  81.             if(state == 'SUCCESS'){
  82.                 var result = response.getReturnValue();                
  83.                 var wrapListItems = component.get( "v.wrapListItems" );
  84.                 component.set( "v.wrapListItems", wrapListItems );
  85.                 helper.refreshView(component);
  86.                 //alert('record deleted successfully');                
  87.                 var eventToast = $A.get("e.force:showToast");
  88.                 eventToast.setParams({
  89.                     "title":'Success',
  90.                     "type":'success',
  91.                     "message":'Record deleted successfully.'
  92.                    });
  93.                  eventToast.fire();
  94.             }
  95.         });
  96.         $A.enqueueAction(action);
  97.     },   
  98.  
  99.     })

Step 3:- Create Lightning Component : wrapperClassCustomObjCmpHelper.js

From Developer Console >> File >> New >> Lightning Component >> JavaScript Helper

wrapperClassCustomObjCmpHelper.js [JavaScript Helper File]

  1.    ({
  2. 	refreshView : function(component, event, helper) {
  3. 		var action = component.get("c.appCustomWrapListMthd"); 
  4.  
  5.         action.setCallback(this, function(response){
  6.             var state = response.getState();            
  7.             if(state=='SUCCESS'){
  8.                 var result = response.getReturnValue();               
  9.                 component.set('v.wrapListItems',result);
  10.             }
  11.         });
  12.         $A.enqueueAction(action);
  13. 	}
  14.   })

Step 4:- Create Lightning Component : wrapperClassCustomObjCmp.css

From Developer Console >> File >> New >> Lightning Component >> Component Style CSS

wrapperClassCustomObjCmp.css [Lightning Component File]

Note:-Static resource zip file

You need to change $Resource.SLDS2016 with your SLDS zip file name (static resource zip file Name)

  1.    .THIS {
  2. }
  3. .THIS .slds-table thead tr th{background-color:#eee;}
  4. .THIS .slds-table thead tr th, .THIS .slds-table tbody tr td {border:1px #dddbda solid; border-collapse: collapse; white-space: normal;}
  5.  
  6. .THIS .editSpan:before{content:''; width:17px; height:17px; display:inline-block; background:url(https://www.w3web.net/wp-content/uploads/2022/01/edit_120.png) no-repeat left top; background-size:cover; cursor: pointer;}
  7. .THIS .saveSpan:before{content:''; width:17px; height:11px; display:inline-block; background:url(https://www.w3web.net/wp-content/uploads/2022/01/SaveToCloud.png) no-repeat left top; background-size:cover; cursor: pointer;}
  8. .THIS .delSpan:before{content:''; width:17px; height:17px; display:inline-block; background:url(https://www.w3web.net/wp-content/uploads/2022/01/delete.png) no-repeat left top; background-size:cover; cursor: pointer;}
  9. .THIS .cancelSpan:before{content:''; width:17px; height:17px; display:inline-block; background:url(https://www.w3web.net/wp-content/uploads/2022/01/closeIcon.png) no-repeat left top; background-size:cover; cursor: pointer;}
  10. .THIS .createRecord:before{content:''; width:15px; height:17px; display:inline-block; background:url(https://www.w3web.net/wp-content/uploads/2022/01/createRecordIcon.png) no-repeat left top; background-size:cover; cursor: pointer;}

Step 5:- Create Lightning Application : wrapperCustomObjCtrCmp.apxc

From Developer Console >> File >> New >> Apex Class

wrapperCustomObjCtrCmp.apxc [Apex Class Controller]

  1.    public class wrapperCustomObjCtrCmp {    
  2.  
  3.     public class wrapperCustomClass{
  4.         @AuraEnabled
  5.         public string studentName;
  6.         @AuraEnabled
  7.         public string studentEmail;
  8.         @AuraEnabled
  9.         public string studentAddress;
  10.         @AuraEnabled
  11.         public Id recStudentId;        
  12.         @AuraEnabled
  13.         public BOOLEAN editMode;
  14.  
  15.         public wrapperCustomClass(string studentName, string studentEmail, string studentAddress, Id recStudentId,BOOLEAN editMode){
  16.          this.studentName = studentName;
  17.          this.studentEmail = studentEmail;
  18.          this.studentAddress = studentAddress;  
  19.          this.recStudentId = recStudentId;           
  20.          this.editMode=editMode;
  21.         }
  22.  
  23.     }
  24.  
  25.  
  26.     @AuraEnabled
  27.     public static List<wrapperCustomClass> appCustomWrapListMthd(){
  28.        List<NewStudent__c> newStudent = NEW List<NewStudent__c>();       
  29.        List<wrapperCustomClass> custWrapObj = NEW  List<wrapperCustomClass>();            
  30.        List<NewStudent__c> newStudentView =[SELECT Id, Name, Email__c, Address__c FROM NewStudent__c];
  31.  
  32.         FOR(NewStudent__c studentObj:newStudentView){            
  33.            custWrapObj.add(NEW wrapperCustomClass(studentObj.Name, studentObj.Email__c,studentObj.Address__c, studentObj.Id, FALSE));   
  34.         }
  35.         RETURN custWrapObj;
  36.     }
  37.  
  38.  
  39.     @AuraEnabled
  40.     public static List<NewStudent__c> delectRecId(Id delRecId){
  41.         DELETE [SELECT Id FROM NewStudent__c WHERE Id=:delRecId];        
  42.         List<NewStudent__c> listStudent = [SELECT Id, Name, Email__c, Address__c FROM NewStudent__c];        
  43.         RETURN listStudent;       
  44.     }    
  45.  
  46.     @AuraEnabled
  47.     public static NewStudent__c saveEdited(string editName, string editAddress, string editEmail, Id recId){
  48.         system.debug('==recId=='+recId);
  49.  
  50.         NewStudent__c newStudentView =[SELECT Id, Name, Email__c, Address__c FROM NewStudent__c WHERE Id=:recId];
  51.         newStudentView.Name = editName;
  52.         newStudentView.Address__c= editAddress;
  53.         newStudentView.Email__c= editEmail;
  54.         UPDATE newStudentView;
  55.         RETURN newStudentView;        
  56.     }
  57.  }

 

Further post that would you like to learn in Salesforce

 

 

 

FAQ (Frequently Asked Questions)

How do I save a report in Salesforce?

Go into the report that you want to clone. Click Customize. Change the parameters that will make the report unique and Click Save As 'new report filename'.

How do I edit Inlines in Salesforce?

Before your users can start inline editing, the option must be turned on in your Salesforce org. To do this, from setup, go to User Interface and then check the box for 'Enable Inline Editing.' The ability to inline edit is per Salesforce org and cannot be turned on only for specific profiles or users.

What is inline editing?

Inline Editing is a feature that allows users to seamlessly edit and write content visually and directly on-screen without having to toggle between a 'read-only' view and an 'edit' view. In short, users can make quick changes or create content without going to a new page.

Related Topics | You May Also Like

 
Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
 
 
  

Our Free Courses →

👉 Get Free Course →

📌 Salesforce Administrators

📌 Salesforce Lightning Flow Builder

📌 Salesforce Record Trigger Flow Builder

👉 Get Free Course →

📌 Aura Lightning Framework

📌 Lightning Web Component (LWC)

📌 Rest APIs Integration



Hi, This is Vijay Kumar behind the admin and founder of w3web.net. I am a senior software developer and working in MNC company from more than 8 years. I am great fan of technology, configuration, customization & development. Apart of this, I love to write about Blogging in spare time, Working on Mobile & Web application development, Salesforce lightning, Salesforce LWC and Salesforce Integration development in full time. [Read full bio] | | The Sitemap where you can find all published post on w3web.net

Leave a Comment