Lightning Web Components(LWC)에서 lwc:if 를 사용해서 RecordType에 따라 조건부 렌더링 (Conditional Rendering) 사용법과 Aura가 감싼 Lwc 에서 어떻게 Save처리 하는지 알아보도록 하겠습니다.
lwc:if를 사용한 조건부 렌더링 이해하기
<template>
<template lwc:if={property1}> Statement1 </template>
<template lwc:elseif={property2}> Statement2 </template>
<template lwc:else> Statement3 </template>
</template>
코드만 보아도 직관적으로 이해할 수 있는 내용입니다.
property1가 true이면 Statement 1이 렌더링이 되고 false이면 2번 째 조건을 확인하고 렌더링합니다.
elseif와 else는 선택사항
공식 문서에 따르면 elseif와 else는 optional 합니다. 즉 if문 하나만 작성해도 괜찮습니다.
Switch문을 사용한 RecordType 처리
이전에 RecordTypeName 가져온거 기억하시나요?
https://loitering.tistory.com/52
세일즈포스 커스텀 레코드 생성 만들기 2 - 모달 속 LWC 구현 및 컨트롤러 연결
지난글에 이어 (1) 모달 속 레이아웃 기본적인 구성과 (2) 컨트롤러를 만들어 오브젝트에 레코드 타입이 존재하는 경우 Aura에서 어떻게 받아오는지 다루도록 하겠습니다.모달 구현LWCleadRecordCreati
loitering.tistory.com
Switch 문을 사용하여 RecordType에 따라 렌더링할 내용을 결정할 수 있습니다. 예를 들어, Business Lead인 경우에만 "How Did You Find Out About Us?" 필드를 노출 시킬 수 있습니다.
checkRecordType(){
switch (this.recordTypeName){
case "Business":
this.isBusinessLead = true;
this.isPersonLead = false;
break;
case "Person":
this.isBusinessLead = false;
this.isPersonLead = true;
break;
}
}
조건부 렌더링 추가
그리고 위에서 본 예시를 바탕으로 조건부 렌더링을 추가하여 Business Lead인 경우에만 "How Did You Find Out About Us?" 노출 시키도록 하겠습니다.
<template lwc:if={isBusinessLead}>
<lightning-combobox
name="About Us"
label="How Did You Find Out About Us?"
value={leadChannel}
placeholder="Please select one"
options={leadChannelOptions}
onchange={inputChangHandler} ></lightning-combobox>
</template>
위 코드를 적용하니 Person Lead인 경우 아래 왼쪽 화면, Business Lead인 경우 아래 오른쪽 화면처럼 렌더링 되는 것을 확인할 수가 있습니다.
Aura가 감싼 LWC에서 Save 처리
현재 구조
위 화면은 작업 초기 모습입니다.
현재 작업 중인 구조는 Aura가 LWC를 감싸고 있는 구조입니다. Save 버튼을 눌렀을 때 데이터를 어디서 처리할지 고민해야 합니다.
- Lwc -> Aura -> Apex: LWC에서 입력 받은 값을 Aura로 넘겨주고 다시 Apex로 넘겨주는 번거로운 작업입니다. 권장하지 않습니다.
- Lwc -> Apex: LWC에서 Apex로 값을 직접 넘겨주는 것이 좋습니다.
Aura에서 자식 Lwc 함수 호출
Save를 눌렀을 때 자식 Lwc (LeadRecordCreationForm)의 함수를 호출하고자 합니다.
함수가 호출되면 Lwc에서 입력 받은 값을 Apex Controller (LeadRecordCreationFormController)로 넘겨줄겁니다.
우선 자식 LWC에 aura:id를 추가하여 특정 컴포넌트에 접근할 수 있도록 합니다. 그런 다음, 자식 LWC의 saveRecord 함수를 호출합니다.
// LeadRecordCreationContainer
<aura:if isTrue="{!v.isReadyToLoadLwc}">
<c:leadRecordCreationForm aura:id="leadRecordCreationFormLWC" // aura:id 추가
recordTypeId = "{!v.recordTypeId}"
recordTypeName = "{!v.recordTypeName}"/>
</aura:if>
aura:id를 사용해서 자식 Lwc를 선택하고 자식 lwc의 saveRecord를 실행할겁니다.
//LeadRecordCreationContainerController
handleSaveClick: function(component, event, recordData) {
var childComponent = component.find('leadRecordCreationFormLWC');
childComponent.saveRecord();
}
saveRecord 함수 구현
이제 LeadRecordCreationForm에서 saveRecord를 구현 해봅시다.
// LeadRecordCreationForm
@api
saveRecord() {
if((this.lastName == undefined || this.lastName == '') ||
(this.email == undefined || this.email == '') ||
(this.phone == undefined || this.phone == '')
){
this.dispatchEvent(
new ShowToastEvent({
variant: 'warning',
title: 'Warning',
message: 'Oops! You didn\'t fill in some fields! '
})
);
}else{
let leadRecord = {
FirstName: this.firstName,
LastName: this.lastName,
Email: this.email,
Phone: this.phone,
HowKnowUs: this.isBusinessLead ? this.leadChannel : null,
RecordTypeId: this.recordTypeId
};
createLeadRecord({leadInfo : JSON.stringify(leadRecord)})
.then(result => {
this.dispatchEvent(
new ShowToastEvent({
variant: 'success',
title: 'Success',
message: result
})
);
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: result,
objectApiName: 'Lead',
actionName: 'view'
}
});
})
.catch(error => {
this.dispatchEvent(
new ShowToastEvent({
variant: 'error',
title: 'Failed',
message: error.message
})
);
})
}
}
- lastName, email, phone 값 중 하나라도 입력이 안 되면 경고창을 보여줄겁니다.
- leadRecord에 Object 타입으로 입력 받은 값들을 담아 한번에 넘겨줄겁니다.
- Apex controller에 createLeadRecord 함수를 호출합니다.
- 함수 호출해서 정상적으로 처리되면 Success를 창을 보여주고 새롭게 생성된 리드 디테일 페이지를 NavigationMixin.Navigate를 이용해 이동합니다.
- 만약 에러가 뜰 경우 Failed라는 에러창을 보여줄겁니다.
export default class LeadRecordCreationForm extends NavigationMixin(LightningElement)
- NavigationMixin.Navigate을 사용하기 위해서 extends 부분을 위와 같이 수정해야 합니다.
Apex createLeadRecord
@AuraEnabled
public static String createLeadRecord(String leadInfo){
if(String.isEmpty(leadInfo)) return null;
Map<String, Object> jsonData = (Map<String, Object>) JSON.deserializeUntyped(leadInfo);
String firstName = (String) jsonData.get('FirstName');
String lastName = (String) jsonData.get('LastName');
String email = (String) jsonData.get('Email');
String phone = (String) jsonData.get('Phone');
String howKnowUs = (String) jsonData.get('HowKnowUs');
String recordTypeId = (String) jsonData.get('RecordTypeId');
Lead sLead = new Lead();
sLead.FirstName = firstName;
sLead.LastName = lastName;
sLead.Email = email;
sLead.Phone = phone;
sLead.HowDidYouFindOutAboutUs__c = howKnowUs;
sLead.RecordTypeId = recordTypeId;
try{
insert sLead;
}catch (DmlException ex){
return ex.getMessage();
}
return sLead.Id;
}
String leadInfo는 아래 모습으로 들어옵니다.
{Email=bonJ@bonjovi.net, FirstName=Bon, HowKnowUs=null, LastName=Jovi, Phone=12233333333, RecordTypeId=0125h000001ZOKnAAO}
Lead 생성 테스트
리드 생성 후 값 초기화
리드 생성이 정상적으로 완료된 후 다시 생성 버튼을 누르면 이전에 입력했던 값이 그대로 남아있는 경우가 있습니다. 이를 방지하기 위해 값을 초기화하는 로직을 추가합니다.
createLeadRecord({leadInfo : JSON.stringify(leadRecord)})
.then(result => {
this.dispatchEvent(
new ShowToastEvent({
variant: 'success',
title: 'Success',
message: result
})
);
this.valueClear(); // 함수 호출 추가
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: result,
objectApiName: 'Lead',
actionName: 'view'
}
});
})
.catch(error => {
this.dispatchEvent(
new ShowToastEvent({
variant: 'error',
title: 'Failed',
message: error.message
})
);
})
.then으로 들어와서 Success 메시지를 보여주고 페이지 이동하기 전 값을 초기화하는 함수를 호출하도록 하였습니다.
valueClear(){
this.firstName = '';
this.lastName = '';
this.email = '';
this.phone = '';
this.leadChannel = '';
this.isPersonLead = false;
this.isBusinessLead = false;
}
다음 포스트에서는 Apex의 Wrapper를 다루어보겠습니다.
createLeadRecord 보시면 deserializeUntyped 후 jsonData.get을 통해 값을 하나 하나 가져오고 있습니다.
좀 더 효율적인 방법으로 처리해보도록 하겠습니다.
'Salesforce > 개발_한국어' 카테고리의 다른 글
세일즈포스 LWC로 lightning-map 활용한 지도 구현 가이드 (1부) (0) | 2024.07.24 |
---|---|
세일즈포스 Apex Wrapper (0) | 2024.07.22 |
세일즈포스 커스텀 레코드 생성 만들기 3 - LWC에서 handler 연결 및 Picklist 값 가져오기 (2) | 2024.06.02 |
세일즈포스 커스텀 레코드 생성 만들기 2 - 모달 속 LWC 구현 및 컨트롤러 연결 (0) | 2024.05.26 |
세일즈포스 커스텀 레코드 생성 만들기 1 - Standard Button 연결 및 모달 구현 (Custom Record Creation Form) (0) | 2024.05.19 |