Upload documents
<script>
import { LightningElement, api, wire, track } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { getRelatedFiles } from 'lightning/uiRelatedListApi';
import { createRecord } from 'lightning/uiRecordApi';
import CONTENT_DOCUMENT_LINK_OBJECT from '@salesforce/schema/ContentDocumentLink';
import LINKED_ENTITY_ID_FIELD from '@salesforce/schema/ContentDocumentLink.LinkedEntityId';
import CONTENT_DOCUMENT_ID_FIELD from '@salesforce/schema/ContentDocumentLink.ContentDocumentId';
export default class UploadOrSelectFile extends LightningElement {
@api recordId;
@track files = [];
@wire(getRelatedFiles, { recordId: '$recordId' })
wiredFiles({ error, data }) {
if (data) {
this.files = data.map(file => ({
label: file.Title,
value: file.ContentDocumentId
}));
} else if (error) {
console.error('Error fetching files:', error);
}
}
handleUploadFinished(event) {
const uploadedFiles = event.detail.files;
this.showToast('Success', `${uploadedFiles.length} file(s) uploaded successfully.`, 'success');
}
handleFileSelection(event) {
const selectedFileId = event.target.value;
this.linkFileToRecord(selectedFileId);
}
linkFileToRecord(fileId) {
const fields = {};
fields[LINKED_ENTITY_ID_FIELD.fieldApiName] = this.recordId;
fields[CONTENT_DOCUMENT_ID_FIELD.fieldApiName] = fileId;
const recordInput = { apiName: CONTENT_DOCUMENT_LINK_OBJECT.objectApiName, fields };
createRecord(recordInput)
.then(() => {
this.showToast('Success', 'File linked successfully.', 'success');
})
.catch(error => {
this.showToast('Error', 'Failed to link file.', 'error');
console.error('Error linking file:', error);
});
}
showToast(title, message, variant) {
this.dispatchEvent(
new ShowToastEvent({
title,
message,
variant
})
);
}
}
</script>
<template>
<lightning-card title="Upload or Select File">
<div class="slds-m-around_medium">
<!-- File Upload -->
<lightning-file-upload
label="Upload File"
record-id={recordId}
onuploadfinished={handleUploadFinished}
multiple>
</lightning-file-upload>
<!-- Select Existing File -->
<template if:true={files.length}>
<lightning-combobox
name="fileSelect"
label="Select Existing File"
options={files}
onchange={handleFileSelection}>
</lightning-combobox>
</template>
</div>
</lightning-card>
</template>
Upload documents
Reviewed by dasfrogpractice
on
09:28
Rating:
No comments: