Salesforce 在Lightning组件中添加删除行动态:示例代码

导读:本篇文章讲解 Salesforce 在Lightning组件中添加删除行动态:示例代码,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

📖摘要


今天分享下 —— Salesforce 在Lightning组件中添加删除行动态:示例代码 的一些基本知识,欢迎关注!

在这篇文章中,我们将学习如何使用客户端 JavaScript 控制器在 Salesforce Lightning 组件中动态添加删除行。

在本文中,我们创建了2个示例闪电组件,这些闪电组件 可以通过在UI上添加或删除新行来根据需要创建多个记录。我们还将输入“名字”作为必填字段

在这里插入图片描述

组件构成:
在这里插入图片描述


🌂分享

为此,我们 创建了2个闪电组件和2个闪电事件,用于从子组件到父组件的传递值/操作。事件可以包含可以在触发事件之前设置的属性,并可以在处理事件时读取。

  1. 步骤1:创建闪电事件: AddNewRowEvt .evt 从开发人员控制台>>文件>>新建>> 闪电事件

AddNewRowEvt

<aura:event type="COMPONENT" description="Use For Add New Row"></aura:event>
  1. 步骤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>
  1. 步骤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();
    }, 
  
})
  1. 步骤4:创建Apex控制器: addDeleteController .apxc 从开发人员控制台>>文件>>新建>> Apex类
public with sharing class addDeleteController {
   @AuraEnabled
    public static void saveContacts(List<Contact> ListContact){
        Insert ListContact;
    }
}
  • 通过上面的顶点控制器,我们可以保存联系人。
  1. 步骤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>

在这里插入图片描述


🎉最后

  • 更多参考精彩博文请看这里:《陈永佳的博客》

  • 喜欢博主的小伙伴可以加个关注、点个赞哦,持续更新嘿嘿!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/97396.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!