📖摘要
今天分享下 —— Salesforce 在Lightning組件中添加刪除行動態:示例代碼 的一些基本知識,歡迎關注!
在這篇文章中,我們將學習如何使用客戶端
JavaScript
控制器在Salesforce Lightning
組件中動態添加刪除行。
在本文中,我們創建了2個示例閃電組件,這些閃電組件 可以通過在UI上添加或刪除新行來根據需要創建多個記錄。我們還將輸入“名字”作爲必填字段
組件構成:
🌂分享
爲此,我們 創建了2個閃電組件和2個閃電事件,用於從子組件到父組件的傳遞值/操作
。事件可以包含可以在觸發事件之前設置的屬性,並可以在處理事件時讀取。
- 步驟1:創建閃電事件:
AddNewRowEvt .evt
從開發人員控制檯>>文件>>新建>> 閃電事件
AddNewRowEvt
<aura:event type="COMPONENT" description="Use For Add New Row"></aura:event>
- 步驟2:建立閃電事件:
DeleteRowEvt .evt
從開發人員控制檯>>文件>>新建>> 閃電事件
DeleteRowEvt
<aura:event type="COMPONENT" description="Event to remove Row" >
<aura:attribute name="indexVar" type="Integer" description="Use For Delete Row" />
</aura:event>
- 步驟3:創建Lightning組件:
dynamicRowItem.cmp
[子組件]從開發人員控制檯>>文件>>新建>> Lightning組件
Child Component
<!-- sfdcMonkey.com -->
<!-- Child Lightning Component for Create New Row Instance-->
<aura:component >
<!-- Aura Attribute for store single Contact[standard Object] Instance
And Store Index of Particular Instance -->
<aura:attribute name="ContactInstance" type="Contact"/>
<aura:attribute name="rowIndex" type="String"/>
<!-- Register 2 Lightning Event for handle add or Delete rows on Parent Component -->
<aura:registerEvent name="DeleteRowEvt" type="c:DeleteRowEvt"/>
<aura:registerEvent name="AddRowEvt" type="c:AddNewRowEvt"/>
<!-- Table Row -->
<tr class="slds-text-title_caps">
<td>
{!v.rowIndex + 1}
</td>
<td>
<ui:inputText class="slds-input" value="{!v.ContactInstance.FirstName}"/>
</td>
<td>
<ui:inputText class="slds-input" value="{!v.ContactInstance.LastName}"/>
</td>
<td>
<ui:inputPhone class="slds-input" value="{!v.ContactInstance.Phone}"/>
</td>
<td>
<!-- conditionally Display Add or Delete Icons
if rowIndex is 0 then show Add New Row Icon else show delete Icon
-->
<aura:if isTrue="{!v.rowIndex == 0}">
<a onclick="{!c.AddNewRow}">
<lightning:icon iconName="utility:add" class="slds-icon slds-icon_small" size="small" alternativeText="add"/>
<span class="slds-assistive-text">Add Icon</span>
</a>
<aura:set attribute="else">
<a onclick="{!c.removeRow}">
<lightning:icon variant="error" iconName="utility:delete" class="slds-icon slds-icon_small" size="small" alternativeText="icon"/>
<span class="slds-assistive-text">Delete Icon</span>
</a>
</aura:set>
</aura:if>
</td>
</tr>
</aura:component>
JavaScript控制器: dynamicRowItemController.js
javaScript Controller
({
AddNewRow : function(component, event, helper){
// fire the AddNewRowEvt Lightning Event
component.getEvent("AddRowEvt").fire();
},
removeRow : function(component, event, helper){
// fire the DeleteRowEvt Lightning Event and pass the deleted Row Index to Event parameter/attribute
component.getEvent("DeleteRowEvt").setParams({"indexVar" : component.get("v.rowIndex") }).fire();
},
})
- 步驟4:創建Apex控制器:
addDeleteController .apxc
從開發人員控制檯>>文件>>新建>> Apex類
public with sharing class addDeleteController {
@AuraEnabled
public static void saveContacts(List<Contact> ListContact){
Insert ListContact;
}
}
- 通過上面的頂點控制器,我們可以保存聯繫人。
- 步驟5:創建
Lightning
組件:dynamicRow.cmp
[父組件]從開發人員控制檯>>文件>>新建>> Lightning組件
<!--sfdcmonkey.com-->
<!--Parent Lightning Compomemt-->
<aura:component controller="addDeleteController" Implements="flexipage:availableForRecordHome,force:hasRecordId">
<!--Init handler which is call doInit js function on component Load-->
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<!--Event handler for Add and Delete Row Event which is fire from Child Component-->
<aura:handler name="DeleteRowEvt" event="c:DeleteRowEvt" action="{!c.removeDeletedRow}"/>
<aura:handler name="AddRowEvt" event="c:AddNewRowEvt" action="{!c.addNewRow}"/>
<!--Aura Attribute for store Contact Object List as Array-->
<aura:attribute name="contactList" type="Contact[]"/>
<!--Header Part-->
<div class="slds-page-header">
<h1 class="slds-page-header__title">Create Multiple Contacts, With Add/Delete Rows Dynamically</h1>
<p class="slds-text-body_small slds-line-height_reset">By sfdcmonkey.com</p>
</div>
<!--Table Part-->
<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">S.No</div>
</th>
<th scope="col">
<div class="slds-truncate" title="First Name">First Name</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Last Name">Last Name</div>
</th>
<th scope="col">
<div class="slds-truncate" title="Phone">Phone</div>
</th>
</tr>
</thead>
<tbody>
<!--Iterate the child Component for display Table rows
with pass the List Item Index for track the Every child Component
and pass each List Contact Instance -->
<aura:iteration items="{!v.contactList}" var="item" indexVar="index">
<c:dynamicRowItem ContactInstance="{!item}" rowIndex="{!index}" />
</aura:iteration>
</tbody>
</table>
<br/>
<!--Save Button which is call Save js function on click -->
<button class="slds-button slds-button_brand" onclick="{!c.Save}">Save</button>
</aura:component>
JavaScript控制器: dynamicRowController.js
JavaScript Controller
({
// function call on component Load
doInit: function(component, event, helper) {
// create a Default RowItem [Contact Instance] on first time Component Load
// by call this helper function
helper.createObjectData(component, event);
},
// function for save the Records
Save: function(component, event, helper) {
// first call the helper function in if block which will return true or false.
// this helper function check the "first Name" will not be blank on each row.
if (helper.validateRequired(component, event)) {
// call the apex class method for save the Contact List
// with pass the contact List attribute to method param.
var action = component.get("c.saveContacts");
action.setParams({
"ListContact": component.get("v.contactList")
});
// set call back
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
// if response if success then reset/blank the 'contactList' Attribute
// and call the common helper method for create a default Object Data to Contact List
component.set("v.contactList", []);
helper.createObjectData(component, event);
alert('record Save');
}
});
// enqueue the server side action
$A.enqueueAction(action);
}
},
// function for create new object Row in Contact List
addNewRow: function(component, event, helper) {
// call the comman "createObjectData" helper method for add new Object Row to List
helper.createObjectData(component, event);
},
// function for delete the row
removeDeletedRow: function(component, event, helper) {
// get the selected row Index for delete, from Lightning Event Attribute
var index = event.getParam("indexVar");
// get the all List (contactList attribute) and remove the Object Element Using splice method
var AllRowsList = component.get("v.contactList");
AllRowsList.splice(index, 1);
// set the contactList after remove selected row element
component.set("v.contactList", AllRowsList);
},
})
JavaScript helper: dynamicRowHelper.js
helper controller code
({
createObjectData: function(component, event) {
// get the contactList from component and add(push) New Object to List
var RowItemList = component.get("v.contactList");
RowItemList.push({
'sobjectType': 'Contact',
'FirstName': '',
'LastName': '',
'Phone': ''
});
// set the updated list to attribute (contactList) again
component.set("v.contactList", RowItemList);
},
// helper function for check if first Name is not null/blank on save
validateRequired: function(component, event) {
var isValid = true;
var allContactRows = component.get("v.contactList");
for (var indexVar = 0; indexVar < allContactRows.length; indexVar++) {
if (allContactRows[indexVar].FirstName == '') {
isValid = false;
alert('First Name Can\'t be Blank on Row Number ' + (indexVar + 1));
}
}
return isValid;
},
})
- 從開發人員控制檯>>文件>>新增>> Lightning應用程序
demo.app
[ 閃電應用 ]
Lightning application
<aura:application extends="force:slds">
<c:dynamicRow/>
<!-- here c: is org. default namespace prefix-->
</aura:application>
🎉最後
-
更多參考精彩博文請看這裏:《陳永佳的博客》
-
喜歡博主的小夥伴可以加個關注、點個贊哦,持續更新嘿嘿!