Lightning Web Component(LWC)의 자바스크립트에서 input 핸들러를 구현하고, Combobox에 Picklist 값을 가져와 넣어보도록 하겠습니다.
Input Handler 구현
<!-- Lead Record Creation Form -->
<template>
<lightning-record-edit-form object-api-name="Lead">
<lightning-messages></lightning-messages>
<lightning-input type="text" label="First Name" onchange={inputChangHandler} value={firstName}></lightning-input>
<lightning-input type="text" label="Last Name" onchange={inputChangHandler} value={lastName} required></lightning-input>
<lightning-input type="email" label="Email" placeholder="Type here..." onchange={inputChangHandler} value={email} required></lightning-input>
<lightning-input type="tel" label="Phone" pattern="[0-9]{3}[0-9]{4}[0-9]{4}" onchange={inputChangHandler} value={phone}></lightning-input>
<lightning-combobox
name="About Us"
label="How Did You Find Out About Us?"
value={leadChannel}
placeholder="Please select one"
options={options}
onchange={inputChangHandler} ></lightning-combobox>
</lightning-record-edit-form>
</template>
- 각 input과 combobox에 onchange 및 value에 커스텀으로 만든 함수와 변수에 맵핑 작업을 하였습니다.
export default class LeadRecordCreationForm extends LightningElement {
@api recordTypeId;
@api recordTypeName;
firstName = '';
lastName = '';
email = '';
phone = '';
leadChannel = '';
connectedCallback() {
}
inputChangHandler(event){
switch (event.target.label){
case 'First Name':
this.firstName = event.target.value;
break;
case 'Last Name':
this.lastName = event.target.value;
break;
case 'Email':
this.email = event.target.value;
break;
case 'Phone':
this.phone = event.target.value;
break;
case 'Phone':
this.leadChannel = event.target.value;
break;
default:
break;
}
}
}
각 input을 담당하는 핸들러를 여러개 만들어 관리하는 방법이 있지만 동일한 로직이 수행되기에 하나의 핸들러를 만들어 관리하는 방향으로 구현하였습니다.
Picklist를 LWC Combobox에 담기
Combobox는 Picklist 같은 역할을 해줍니다. 지난 포스트에서 'How Did You Find Out About Us?' 필드를 생성해주었습니다.
그렇다면 그 값들을 어떻게 불러와야 할까요?
Apex에서 Picklist Value 가져오기
Apex
public with sharing class LeadRecordCreationFormController {
@AuraEnabled
public static String getRecordTypeName (String recordTypeId){
if(recordTypeId == null) return null;
return Schema.getGlobalDescribe().get('Lead').getDescribe().getRecordTypeInfosById().get(recordTypeId).getName();
}
@AuraEnabled
public static Map<String, String> getLeadChannelPicklist(){
Schema.DescribeFieldResult fieldResult = Lead.HowDidYouFindOutAboutUs__c.getDescribe();
List<Schema.PicklistEntry> picklistValues = fieldResult.getPicklistValues();
Map<String, String> resultMap = new Map<String, String>();
for(Schema.PicklistEntry entry : picklistValues){
resultMap.put(entry.label, entry.value);
}
return resultMap;
}
}
getLeadChannelPicklist 함수를 새롭게 추가해 Picklist를 가져오도록 하였습니다.
- Schema.DescribeFieldResult를 통해 특정 오브젝트의 특정 필드의 정보를 가져올 수 있습니다.
- getPicklistValues를 통해 가져온 후 새롭게 생성한 Map에 lable을 키 값으로 value를 value 값으로 넣어줍니다.
- Label이 화면에 표시될 값 입니다.
- 참고링크: https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_fields_describe.htm
DescribeFieldResult Class | Apex Reference Guide | Salesforce Developers
Returns the name of the field, similar to the getName method. However, if the field is part of the current namespace, the namespace portion of the name is omitted. Signature public String getLocalName()
developer.salesforce.com
LWC에서 가져온 Picklist 값 Combobox에 넣기
// LeadRecordCreationForm
import {LightningElement, api} from 'lwc';
import getLeadChannelPicklist from '@salesforce/apex/LeadRecordCreationFormController.getLeadChannelPicklist';
export default class LeadRecordCreationForm extends LightningElement {
@api recordTypeId;
@api recordTypeName;
firstName = '';
lastName = '';
email = '';
phone = '';
leadChannel = '';
connectedCallback() {
getLeadChannelPicklist()
.then(result => {
console.log('Result >> ' + JSON.stringify(result));
})
.catch(error => {
console.error('Error >> ' + JSON.stringify(error))
})
}
inputChangHandler(event){
switch (event.target.label){
case 'First Name':
this.firstName = event.target.value;
break;
case 'Last Name':
this.lastName = event.target.value;
break;
case 'Email':
this.email = event.target.value;
break;
case 'Phone':
this.phone = event.target.value;
break;
case 'Phone':
this.leadChannel = event.target.value;
break;
default:
break;
}
}
}
- 최상단에서 Apex에서 새롭개 생성해준 getLeadChannelPicklist 함수를 Import 합니다.
- Initialization에 관련된 로직들은 보통 ConnectedCallback 속에서 진행합니다. 따라서 이 속에다가 getLeadChannelPicklist를 통해 값을 받아오고 -> 받아온 값을 가공하는 로직이 필요합니다.
LWC Combobox 공식 문서에 따르면 Combobox의 Option은 다음의 형태로 들어가야 합니다.
get options() {
return [
{ label: 'New', value: 'new' },
{ label: 'In Progress', value: 'inProgress' },
{ label: 'Finished', value: 'finished' },
];
}
리스트 속 오브젝트 타입이니 가공하는 과정을 가져보도록 하겠습니다.
import {LightningElement, api} from 'lwc';
import getLeadChannelPicklist from '@salesforce/apex/LeadRecordCreationFormController.getLeadChannelPicklist';
export default class LeadRecordCreationForm extends LightningElement {
@api recordTypeId;
@api recordTypeName;
firstName = '';
lastName = '';
email = '';
phone = '';
leadChannel = '';
leadChannelList = [];
connectedCallback() {
getLeadChannelPicklist()
.then(result => {
this.leadChannelList = result; // 받아온 결과를 바로 leadChannelList 할당
})
.catch(error => {
console.error('Error >> ' + JSON.stringify(error))
})
}
inputChangHandler(event){
switch (event.target.label){
case 'First Name':
this.firstName = event.target.value;
break;
case 'Last Name':
this.lastName = event.target.value;
break;
case 'Email':
this.email = event.target.value;
break;
case 'Phone':
this.phone = event.target.value;
break;
case 'Phone':
this.leadChannel = event.target.value;
break;
default:
break;
}
}
get leadChannelOptions(){
let leadChannelOptionList = [];
if(typeof this.leadChannelList !== "undefined" && this.leadChannelList != null){
Object.entries(this.leadChannelList).map(([key, value]) => {
leadChannelOptionList.push({label: key, value: value})
})
}
return leadChannelOptionList;
}
}
- Object.entries: 자바스크립트 객체를 배열로 변환해주는 메소드.
- leadChannelOptionList.push({label: key, value: value})를 통해 option에서 요구하는 형태로 가공하여 밀어 넣습니다.
<!-- Lead Record Creation Form -->
<template>
<lightning-record-edit-form object-api-name="Lead">
<lightning-messages></lightning-messages>
<lightning-input type="text" label="First Name" onchange={inputChangHandler} value={firstName}></lightning-input>
<lightning-input type="text" label="Last Name" onchange={inputChangHandler} value={lastName} required></lightning-input>
<lightning-input type="email" label="Email" placeholder="Type here..." onchange={inputChangHandler} value={email} required></lightning-input>
<lightning-input type="tel" label="Phone" pattern="[0-9]{3}[0-9]{4}[0-9]{4}" onchange={inputChangHandler} value={phone}></lightning-input>
<lightning-combobox
name="About Us"
label="How Did You Find Out About Us?"
value={leadChannel}
placeholder="Please select one"
options={leadChannelOptions} // options 업데이트
onchange={inputChangHandler} ></lightning-combobox>
</lightning-record-edit-form>
</template>
오늘 작업을 통해 사용자로부터 적절히 데이터를 입력 받을 수 있는 준비가 완성되었습니다.
다음 포스트에서는 (1) 지난번에 가져왔던 레코드 타입 정보를 바탕으로 'How Did You Find Out About Us?'를 숨겨보고 (2) Save 구현을 해보도록 하겠습니다.
'Salesforce > 개발_한국어' 카테고리의 다른 글
세일즈포스 Apex Wrapper (0) | 2024.07.22 |
---|---|
세일즈포스 커스텀 레코드 생성 만들기 4 - lwc:if 및 Save 구현 (0) | 2024.06.30 |
세일즈포스 커스텀 레코드 생성 만들기 2 - 모달 속 LWC 구현 및 컨트롤러 연결 (0) | 2024.05.26 |
세일즈포스 커스텀 레코드 생성 만들기 1 - Standard Button 연결 및 모달 구현 (Custom Record Creation Form) (0) | 2024.05.19 |
세일즈포스 Git 연동하기 (IntelliJ & Illuminated Cloud) (0) | 2024.05.13 |