Record에 추가한 이미지를 LWC에서 불러오기

ahncheer·2022년 10월 25일
0

LWC & LWR

목록 보기
23/45

● 실행 화면 미리보기

● 세팅과 코드 작성

→ Object Manager > Page Layout > Related Lists > Notes & Attachments

2. Set Up에서 설정 변경

→ General Settings > Salesforce Files Settings
→ Files uploaded to the Attachments related list on records are uploaded as Salesforce Files, not as attachments 체크

3. 이미지 추가

→ 톱니바퀴 아이콘 > Edit Page

→ Relates List를 드래그 해서 추가

→ Save, Activations 클릭해서 저장 후 이미지 등록 (드래그도 됨)

● 코드 작성

※ LWR_CoffeeMenu.cls

global class LWR_CoffeeMenu {
    
    @AuraEnabled(cacheable=true)
    public static List<coffeeMenu> getCoffeeMenu(){
        List<coffeeMenu> returnList = new List<coffeeMenu>();
        List<CoffeeMenu__c> cmObj = [
            SELECT Name
            , Drink_price__c
            , Drink_type__c
            FROM CoffeeMenu__c
        ];
        
        for(CoffeeMenu__c cm :cmObj){
            coffeeMenu an = new coffeeMenu();
            an.coffeeId = cm.Id;
            an.coffeeName = cm.Name;
            an.coffeeFile = [SELECT LinkedEntityId, ContentDocumentId 
                            FROM ContentDocumentLink 
                            WHERE LinkedEntityId = : cm.Id];
            returnList.add(an);
        }
        return returnList;
    }   
    
    global class coffeeMenu {
        @AuraEnabled global String coffeeId {get; set;}
        @AuraEnabled global String coffeeName {get; set;}
        @AuraEnabled global List<ContentDocumentLink> coffeeFile {get; set;}
    }
}

※ lwc028GetRecordImage.html

<template>
    <div class="wrapper">
        <ul class="menu-wrap">
        <template if:true={coffeeMenuList}>
            <template for:each={coffeeMenuList} for:item="item">
                <li key={item.ID}>
                    <img src={item.bgimgStyle} />
                    <h4>{item.coffeeName} </h4>
                </li>
            </template>
        </template>
        </ul>
    </div>
</template>

※ lwc028GetRecordImage.js

import { LightningElement,api,wire,track} from 'lwc';
import getCoffeeMenu from '@salesforce/apex/LWR_CoffeeMenu.getCoffeeMenu';

export default class Lwc028GetRecordImage extends LightningElement {
    coffeeMenuList = [];

    @wire(getCoffeeMenu)
    wiredGetCoffeeMenu({ error, data }) {
      if (data) {
        console.log('-- data returned --');     
        console.log(data);
        this.coffeeMenuList = JSON.parse(JSON.stringify(data));

        this.coffeeMenuList.forEach((el, index) => {
          if(el.coffeeFile.length > 0){
            let documentId = el.coffeeFile[0].ContentDocumentId;
            el.bgimgStyle ='https://developmentaccount-dev-ed.lightning.force.com/sfc/servlet.shepherd/document/download/'+ documentId +'?operationContext=S1';
          }else{
            el.bgimgStyle = '';
          }
        });
        console.log('this.coffeeMenuList : ', this.coffeeMenuList);
      } else if (error) {
        console.log(error);
      }
    }
}

※ lwc028GetRecordImage.css

.wrapper{
    width: 100%;
    max-width: 800px;
    margin: 10px auto;
    background-color: #e7e7e7;
    padding: 20px 10px;
    border-radius: 5px;
    min-height: 200px;
    box-shadow: rgb(99 99 99 / 20%) 0px 2px 8px 0px;
}
.menu-wrap{
    display: grid;
    grid-template-columns:  1fr 1fr 1fr;
    gap: 20px;
}
.menu-wrap li{
    background-color: #FFF;
    overflow: hidden;
    border-radius: 15px;
    box-shadow: rgba(0, 0, 0, 0.16) 0px 1px 4px;
}
.menu-wrap li::marker{
    display: none;
}
.menu-wrap li h4{
    margin: 0;
    text-align: center;
    padding: 0 4px 5px;
    font-size: 10px;
    color: #38383b;
}
.menu-wrap li img{
    width: 100%;
    max-height: 150px;
    object-fit: cover;
    object-position: center;
}

◎ 기타

  • 무료 이미지 출처 → pixabay
  • Apex를 잘 모르기 때문에 틀린 부분이 있을 수 있습니다. (매핑하는 법을 모릅니다.)
  • 여러 이미지를 가져왔지만, 실제로는 0번째 이미지를 사용했습니다. 여러 이미지 중에서 고르는 방법을 추후 고민해봐야 할 것 같습니다.
    let documentId = el.coffeeFile[0].ContentDocumentId;
  • 이미지 파일은 가져왔지만, URL 앞부분을 고정시켜버렸기 때문에, 고정 값이 아닌 값을 지정하는 방법을 고민해야 할 것 같습니다.
    'https://developmentaccount-dev-ed.lightning.force.com/sfc/servlet.shepherd/document/download/'+ documentId +'?operationContext=S1';
profile
개인 공부 기록용.

1개의 댓글

comment-user-thumbnail
2022년 12월 2일

이렇게 이미지를 불러오는 것은 속도가 느리다고 합니다.
필드에 파일을 추가할 수 있는 것 같은데 시도한다면 그쪽으로 해보시는 것도 좋을 것 같습니다.

답글 달기