salesforce lightning零基础学习(十五) 公用组件之 获取表字段的Picklist(多语言)

此篇参考:salesforce 零基础学习(六十二)获取sObject中类型为Picklist的field values(含record type)

我们在lightning中在前台会经常碰到获取picklist的values然后使用select option进行渲染成下拉列表,此篇用于实现针对指定的sObject以及fieldName(Picklist类型)获取此字段对应的所有可用的values的公用组件。因为不同的record type可能设置不同的picklist values,所以还有另外的参数设置针对指定的record type developer name去获取指定的record type对应的Picklist values.

一. PicklistService公用组件声明实现

Common_PicklistController.cls:有三个形参,其中objectName以及fieldName是必填参数,recordTypeDeveloperName为可选参数。

 public without sharing class Common_PicklistController {

     @AuraEnabled(cacheable=true)
public static List<Map<String,String>> getPicklistValues(String objectName, String fieldName,String recordTypeDeveloperName) {
//1. use object and field name get DescribeFieldResult and also get all the picklist values
List<Schema.PicklistEntry> allPicklistValuesByField;
try {
List<Schema.DescribeSobjectResult> objDescriptions = Schema.describeSObjects(new List<String>{objectName});
Schema.SObjectField field = objDescriptions[0].fields.getMap().get(fieldName);
Schema.DescribeFieldResult fieldDescribeResult = field.getDescribe();
allPicklistValuesByField = fieldDescribeResult.getPicklistValues();
} catch (Exception e) {
throw new AuraHandledException('Failed to retrieve values : '+ objectName +'.'+ fieldName +': '+ e.getMessage());
} //2. get all active field name -> label map
List<Map<String,String>> activeOptionMapList = new List<Map<String,String>>();
Map<String,String> optionValue2LabelMap = new Map<String,String>();
List<String> optionValueList;
for(Schema.PicklistEntry entry : allPicklistValuesByField) {
if (entry.isActive()) {
System.debug(LoggingLevel.INFO, '*** entry: ' + JSON.serialize(entry));
optionValue2LabelMap.put(entry.getValue(), entry.getLabel());
}
} //3. generate list with option value(with/without record type)
if(String.isNotBlank(recordTypeDeveloperName)) {
optionValueList = PicklistDescriber.describe(objectName,recordTypeDeveloperName,fieldName);
} else {
optionValueList = new List<String>(optionValue2LabelMap.keySet());
} //4. generate and format result
if(optionValueList != null) {
for(String option : optionValueList) {
String optionLabel = optionValue2LabelMap.get(option);
Map<String,String> optionDataMap = new Map<String,String>();
optionDataMap.put('value',option);
optionDataMap.put('label', optionLabel);
activeOptionMapList.add(optionDataMap);
}
} return activeOptionMapList;
}
}

Common_PicklistService.cmp:声明了getPicklistInfo方法,有以下三个主要参数.objectName对应sObject的API名字,fieldName对应的此sObject中的Picklist类型的字段,recordTypeDeveloperName对应这个sObject的record type的developer name

 <aura:component access="global" controller="Common_PicklistController">
<aura:method access="global" name="getPicklistInfo" description="Retrieve active picklist values and labels mapping with(without) record type" action="{!c.getPicklistInfoAction}">
<aura:attribute type="String" name="objectName" required="true" description="Object name"/>
<aura:attribute type="String" name="fieldName" required="true" description="Field name"/>
<aura:attribute type="String" name="recordTypeDeveloperName" description="record type developer name"/>
<aura:attribute type="Function" name="callback" required="true" description="Callback function that returns the picklist values and labels mapping as [{value: String, label: String}]"/>
</aura:method>
</aura:component>

Common_PicklistServiceController.js: 获取传递过来的参数,调用后台方法并对结果放在callback中。

 ({
getPicklistInfoAction : function(component, event, helper) {
const params = event.getParam('arguments');
const action = component.get('c.getPicklistValueList');
action.setParams({
objectName : params.objectName,
fieldName : params.fieldName,
recordTypeDeveloperName : params.recordTypeDeveloperName
});
action.setCallback(this, function(response) {
const state = response.getState();
if (state === 'SUCCESS') {
params.callback(response.getReturnValue());
} else if (state === 'ERROR') {
console.error('failed to retrieve picklist values for '+ params.objectName +'.'+ params.fieldName);
const errors = response.getError();
if (errors) {
console.error(JSON.stringify(errors));
} else {
console.error('Unknown error');
}
}
}); $A.enqueueAction(action);
}
})

二. 公用组件调用

上面介绍了公用组件以后,下面的demo是如何调用。

SimplePicklistDemo引入Common_PicklistService,设置aura:id用于后期获取到此component,从而调用方法

 <aura:component implements="flexipage:availableForAllPageTypes">
<!-- include common picklist service component -->
<c:Common_PicklistService aura:id="service"/>
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/> <aura:attribute name="accountTypeList" type="List"/>
<aura:attribute name="accountTypeListByRecordType" type="List"/> <lightning:layout verticalAlign="center" class="x-large">
<lightning:layoutItem flexibility="auto" padding="around-small">
<lightning:select label="account type">
<aura:iteration items="{!v.accountTypeList}" var="type">
<option value="{!type.value}" text="{!type.label}"></option>
</aura:iteration>
</lightning:select>
</lightning:layoutItem> <lightning:layoutItem flexibility="auto" padding="around-small">
<lightning:select label="account type with record type">
<aura:iteration items="{!v.accountTypeListByRecordType}" var="type">
<option value="{!type.value}" text="{!type.label}"></option>
</aura:iteration>
</lightning:select>
</lightning:layoutItem>
</lightning:layout> </aura:component>

SimplePicklistDemoController.js:初始化方法用于获取到公用组件component然后获取Account的type的values,第一个是获取所有的values/labels,第二个是获取指定record type的values/labels。

 ({
doInit : function(component, event, helper) {
const service = component.find('service');
service.getPicklistInfo('Account','type','',function(result) {
component.set('v.accountTypeList', result);
}); service.getPicklistInfo('Account','type','Business_Account',function(result) {
component.set('v.accountTypeListByRecordType',result);
});
}
})

三.效果展示:

1. account type的展示方式

salesforce lightning零基础学习(十五) 公用组件之 获取表字段的Picklist(多语言)

2. account type with record type的展示方式。

salesforce lightning零基础学习(十五) 公用组件之 获取表字段的Picklist(多语言)

总结:篇中介绍了Picklist values针对with/without record type的公用组件的使用,感兴趣的可以进行优化,篇中有错误的欢迎指出,有不懂的欢迎留言。

上一篇:网站常用的一些javascript封装 简化调用


下一篇:Service Cloud零基础学习(二)Entitlement & MileStone