根据记录类型和行业显示记录,如果帐户处于活动状态,则显示绿色按钮图标,使用 lwc 如何实现

问题描述 投票:0回答:1

编写一个LWC组件来显示lightning-datatable中的Account记录并显示复选框 字段 (IsActive) 作为图像(true:绿色对勾,false:红色十字)。请不要使用@wire 适配器。 请在 Lightning-datatable 顶部添加一个包含 3 个下拉菜单的过滤器来处理行过滤。 ● 第一个下拉列表包含帐户上可用记录类型的名称。 ● 第二个下拉列表包含帐户上选项列表类型的可用字段的名称。 ● 第三个下拉列表的值基于记录类型下拉列表和选项列表的选择 下拉菜单。它应该显示所选记录的所选选项列表的可用值 在下拉菜单中输入在此处输入图像描述

我要求使用lwc来实现这个,我实现了直到过滤数据表中的数据,但是如何根据帐户状态显示绿色和红色图标对我来说是一个挑战,有人可以指导我吗

lwc imperative
1个回答
0
投票

我已经研究过这个问题并找到了以下解决方案,我将其与所有代码及其解释一起发布在这里。

  1. 我遵循的方法:

a)首先,我创建了一个 apex 类,它有一个根据记录类型、字段及其各自值获取帐户记录的方法。在调用类时,所有三个值都通过 LWC javascript 的参数传递。

b) 创建了另外两个方法来使用 Schema.describe 方法从 salesforce 获取 recordTypes 和 Picklist 字段及其各自的值,然后在 LWC 上使用它们。

c) LWC JS 文件从 apexclass 导入所有 3 个方法,随后根据要求使用相同创建的适配器。

d)由于不应该使用wire,因此这里使用了命令式顶点调用,这是通过连接的回调进行的。

e) HTML 显示的闪电卡具有 3 个用于记录类型、字段和值选择的下拉菜单,它们的市中心选项由同一组件的 JS 控制,记录的显示面板使用闪电数据表。

f) 我使用 Cellattributes 和动态图标来处理活动和非活动帐户图标显示,并且在数据面板中对两种类型的帐户进行控制。

g) LWC 配置已公开,并将所有 3 种类型的应用程序构建器支持的页面设置为目标。

h) 最后为所使用的控制器创建了一个 apex 测试类,到目前为止,该控制器的代码覆盖率为 72%。

  1. Apex 类、测试类和 LWC 组件的代码片段:

a) 顶级:

public with sharing class AccountController {
   @AuraEnabled(cacheable=true)
   public static List<Account> getAccounts(String recordTypeId, String picklistField, String picklistValue) {
       String query = 'SELECT Id, Name, IsActive__c FROM Account';
      
       if (recordTypeId != null && picklistField != null && picklistValue != null) {
           query += ' WHERE RecordTypeId = :recordTypeId AND ' + picklistField + ' = :picklistValue';
       }
      
       return Database.query(query + ' LIMIT 100');
   }


   @AuraEnabled(cacheable=true)
   public static List<RecordType> getAccountRecordTypes() {
       return [SELECT Id, Name FROM RecordType WHERE SObjectType = 'Account' with SECURITY_ENFORCED];
   }


   @AuraEnabled(cacheable=true)
   public static List<Map<String, String>> getPicklistValues(String picklistField) {
       List<Map<String, String>> picklistOptions = new List<Map<String, String>>();
      
       // Get the field describe result for the picklist field
       Schema.DescribeFieldResult fieldResult = Account.SObjectType.getDescribe().fields.getMap().get(picklistField).getDescribe();
       List<Schema.PicklistEntry> picklistEntries = fieldResult.getPicklistValues();
      
       // Convert PicklistEntry objects to a list of Maps (serializable)
       for (Schema.PicklistEntry entry : picklistEntries) {
           if (entry.isActive()) {
               Map<String, String> picklistOption = new Map<String, String>();
               picklistOption.put('label', entry.getLabel());
               picklistOption.put('value', entry.getValue());
               picklistOptions.add(picklistOption);
           }
       }
      
       return picklistOptions;
   }


}

b) 测试班

@isTest
public class AccountControllerTest {
  
   @isTest
   static void testGetAccountsWithFilter() {
       // Create test data
       RecordType customerRT = [select Id,Name from RecordType where sObjectType='Account' and Name='Customer' with SECURITY_ENFORCED limit 1];
       Schema.SObjectField picklistField = Account.IsActive__c;
      
       Account acc = new Account();
           acc.Name = 'Test Account';
           acc.RecordTypeId = customerRT.Id;
           acc.Type = 'Prospect';
           acc.Industry = 'Education';
       insert acc;


       // Test the getAccounts method with filters
       Test.startTest();
       List<Account> accounts = AccountController.getAccounts(customerRT.Id, 'Type', 'Prospect');
       Test.stopTest();


       // Verify the results
       System.assertNotEquals(null, accounts, 'Accounts should not be null');
       System.assertEquals(1, accounts.size(), 'There should be one account returned');
       System.assertEquals(acc.Id, accounts[0].Id, 'The account Id should match');
   }
  
   @isTest
   static void testGetAccountsWithoutFilter() {
       // Create test data
       Account acc = new Account(Name = 'Test Account', Type = 'Prospect', Industry = 'Education');
       insert acc;


       // Test the getAccounts method without filters
       Test.startTest();
       List<Account> accounts = AccountController.getAccounts(null, null, null);
       Test.stopTest();


       // Verify the results
       System.assertNotEquals(null, accounts, 'Accounts should not be null');
       System.assertEquals(accounts.size() > 0,true);
   }


   @isTest
   static void testGetAccountRecordTypes() {
       // Create test data
       RecordType vendorRT = [select Id,Name from RecordType where sObjectType='Account' and Name='Vendor' with SECURITY_ENFORCED limit 1];


       // Test the getAccountRecordTypes method
       Test.startTest();
       List<RecordType> recordTypes = AccountController.getAccountRecordTypes();
       Test.stopTest();


       // Verify the results
       System.assertNotEquals(null, recordTypes, 'Record types should not be null');
       System.assertEquals(recordTypes.size() > 0, true);
   }
  
   @isTest
   static void testGetPicklistValues() {
       // Create a custom picklist field
       Schema.DescribeFieldResult fieldResult = Account.SObjectType.getDescribe().fields.getMap().get('IsActive__c').getDescribe();
       List<Schema.PicklistEntry> picklistEntries = fieldResult.getPicklistValues();
      
       // Test the getPicklistValues method
       Test.startTest();
       List<Map<String, String>> picklistOptions = AccountController.getPicklistValues('IsActive__c');
       Test.stopTest();


       // Verify the results
       System.assertNotEquals(null, picklistOptions, 'Picklist options should not be null');
       System.assertEquals(picklistOptions.size() > 0, false);
      
       // Validate that picklist values are present and match the picklist entries
       for (Map<String, String> option : picklistOptions) {
           System.assertNotEquals(null, option.get('label'), 'Label should not be null');
           System.assertNotEquals(null, option.get('value'), 'Value should not be null');
       }
   }
}

c) Lightning Web 组件名称:accountDataTable:

I) accountDataTable.js 文件

import { LightningElement, track } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';
import getAccountRecordTypes from '@salesforce/apex/AccountController.getAccountRecordTypes';
import getPicklistValues from '@salesforce/apex/AccountController.getPicklistValues';


export default class AccountDataTable extends LightningElement {
   @track data = [];
   @track columns = [
       { label: 'Account Name', fieldName: 'Name', type: 'text' },
       {
           label: 'Active',
           fieldName: 'IsActive__c',
           cellAttributes: { iconName: { fieldName: 'dynamicIcon' } }
       }
   ];
   @track recordTypes = [];
   @track picklistFields = [];
   @track picklistValues = [];
   @track selectedRecordType = '';
   @track selectedPicklistField = '';
   @track selectedPicklistValue = '';


   connectedCallback() {
       this.fetchRecordTypes();
       this.fetchAccounts();
   }


   fetchRecordTypes() {
       getAccountRecordTypes()
           .then((result) => {
               this.recordTypes = result.map(rt => ({ label: rt.Name, value: rt.Id }));
           })
           .catch((error) => {
               console.error('Error fetching record types: ', error);
           });
   }


   handleRecordTypeChange(event) {
       this.selectedRecordType = event.detail.value;
       this.selectedPicklistField = '';
       this.selectedPicklistValue = '';
       this.picklistValues = [];
       this.fetchPicklistFields();
   }


   fetchPicklistFields() {
       // Replace with your logic to fetch picklist fields (hardcoded or dynamic)
       this.picklistFields = [
           { label: 'Industry', value: 'Industry' },
           { label: 'Type', value: 'Type' },
           // Add other picklist fields here
       ];
   }


   handlePicklistFieldChange(event) {
       this.selectedPicklistField = event.detail.value;
       this.selectedPicklistValue = '';
       this.fetchPicklistValues();
   }


   fetchPicklistValues() {
       getPicklistValues({ recordTypeId: this.selectedRecordType, picklistField: this.selectedPicklistField })
           .then((result) => {
               this.picklistValues = result.map(pv => ({ label: pv.label, value: pv.value }));
           })
           .catch((error) => {
               console.error('Error fetching picklist values: ', error);
           });
   }


   handlePicklistValueChange(event) {
       this.selectedPicklistValue = event.detail.value;
       this.fetchAccounts();
   }


   fetchAccounts() {
       getAccounts({
           recordTypeId: this.selectedRecordType,
           picklistField: this.selectedPicklistField,
           picklistValue: this.selectedPicklistValue
       })
       .then((result) => {
           this.data = result.map(account => {
               return {
                   ...account,
                   IsActive: account.IsActive__c,
                   dynamicIcon : account.IsActive__c ? 'action:approval' : 'action:close',
               };
           });
       })
       .catch((error) => {
           console.error('Error fetching accounts: ', error);
       });
   }
}

II) accountDataTable.html

<!-- sldsValidatorIgnore -->
<!-- accountDataTable.html -->
<template>
   <lightning-card title="Account Data">
       <div class="slds-m-around_medium">
           <lightning-combobox
               name="recordType"
               label="Select Record Type"
               value={selectedRecordType}
               placeholder="Select Record Type"
               options={recordTypes}
               onchange={handleRecordTypeChange}>
           </lightning-combobox>
           <lightning-combobox
               name="picklistField"
               label="Select Picklist Field"
               value={selectedPicklistField}
               placeholder="Select Picklist Field"
               options={picklistFields}
               onchange={handlePicklistFieldChange}>
           </lightning-combobox>
           <lightning-combobox
               name="picklistValue"
               label="Select Picklist Value"
               value={selectedPicklistValue}
               placeholder="Select Picklist Value"
               options={picklistValues}
               onchange={handlePicklistValueChange}>
           </lightning-combobox>
       </div>
       <lightning-datatable
           key-field="Id"
           data={data}
           columns={columns}
           hide-checkbox-column="true"
           draft-values={draftValues}>
       </lightning-datatable>
   </lightning-card>
</template>

III) accountDataTable.js-metaxml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
   <apiVersion>61.0</apiVersion>
   <isExposed>true</isExposed>
   <targets>
       <target>lightning__AppPage</target>
       <target>lightning__RecordPage</target>
       <target>lightning__HomePage</target>
   </targets>
</LightningComponentBundle>

IV) accountDataTable.css

/* accountDataTable.css */
:host {
   display: block;
   margin: 20px;
}


.lightning-datatable {
   margin-top: 10px;
}`enter code here`

希望这有帮助。祝一切顺利!!

© www.soinside.com 2019 - 2024. All rights reserved.