0

Is it possible to map values in lightning datatable fieldname. I'm not able to map the values in the fieldname.

I'm using a lightning-datatable implementation where I'm populating the data and columns from a Apex class where i have used map in return.

Please find the code below:

Apex class

public with sharing class DeleteFileController {
    @AuraEnabled(cacheable=true)
    public static Map<Id, String> getRelatedFilesByRecordId(String recordId) {
        List<ContentDocumentLink> files = [SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId = :recordId];
        List<ID> fileIDs = new List<ID>();
        for (ContentDocumentLink docLink : files)
        {
            fileIDs.add(docLink.ContentDocumentId);
        }
         
        List<ContentVersion> docs = [SELECT ContentDocumentId, FileExtension, Title FROM ContentVersion WHERE ContentDocumentId IN: fileIDs];
        Map<ID, String> mapIdTitle = new Map<ID, String>();
        for(ContentVersion docLink : docs)
        {
            mapIdTitle.put(docLink.ContentDocumentId, docLink.Title);
        }
        return mapIdTitle;
    }
@AuraEnabled
    public static String deleteseletedrecord(Id docIds){
        try{
            System.debug('inside apex class');
            System.debug('docIds : ' + docIds);
            List<ContentDocument> fileList = [SELECT Id FROM ContentDocument WHERE Id = :docIds];
           // delete [SELECT Id FROM ContentDocument WHERE Id = :docIds];
            System.debug('fileList' + fileList[0]);
           delete fileList[0];
            System.debug('fileList' + fileList[0]);
            return 'SUCCESS';
        }
        catch(Exception ex){
            throw new AuraHandledException(ex.getMessage());
        }
    }
 }

here in HTML passing value in data and key-field is going wrong

<template>
    <lightning-card title="Files">
            <div style="height: 250px;">
                <lightning-datatable data={fileList}
                    columns={columns}
                    key-field="fileList.label"
                    onrowselection={handleRowAction}
                    hide-checkbox-column>
                </lightning-datatable>
            </div>
    </lightning-card>
</template>

in JS file

import { LightningElement, wire, api,track } from "lwc";
import getRelatedFilesByRecordId from "@salesforce/apex/DeleteFileController.getRelatedFilesByRecordId";
import deleteSelectedfile from "@salesforce/apex/DeleteFileController.deleteseletedrecord";
import { refreshApex } from '@salesforce/apex';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';

const actions = [
  { label : 'Delete', name : 'delete'},
  { label : 'Upload New Version', name : 'uploadnewversion' },
  { label : 'Edit File', name : 'edit' },
];

const columns = [
  { label : 'FileName', fieldName : 'label'},
  {
      type : 'action',
      typeAttributes : {rowActions : actions},
  },
];  

export default class FileList extends LightningElement {
    @api recordId
    
    @track fileList =[]

    columns = columns;
    error;

    recordIds;
    fileid

    @wire(getRelatedFilesByRecordId, {recordId: '$recordId'})

    wiredResult({data, error}){
      if(data)
      {
        console.log(data)
        this.fileList = Object.keys(data).map(item=>({"label":data[item],"value": item}))
        console.log(JSON.stringify(this.fileList))
      }
      if(error)
      {
        console.log(error)
      }
    }

    handleRowAction(event)
    {
      const actionName = event.detail.action.name;
      console.log('actionName:' , actionName)
      const row = event.detail.row;
      console.log('row:' , row)

      switch(actionName){
        case 'delete':
          this.deleteseletedrecord(row);
          break;

        case 'uploadnewversion':
          this.uploadnewversionfile(row);
          break

        default:
      }
    }

   deleteseletedrecord(currentRow)
    {
      const seletedRow = currentRow;
      console.log('seletedRow:' , seletedRow)

      deleteSelectedfile({'docIds': seletedRow.value})
     // deleteSelectedfile({'docIds': this.fileid})
     // console.log('result: ',result)
      .then(result => {
       // console.log('result: ',result)
        this.dispatchEvent(
          new ShowToastEvent({
            title: 'Success',
            message: 'Selected record is deleted!',
            variant: 'success',
          }),
        );
       // return refreshApex(this.recordId);
       window.location.reload;
      })
      .catch(error => {
        this.message = undefined;
        this.error = error;
        this.dispatchEvent(
          new ShowToastEvent({
            title: 'Error creating records',
            message: error.body.pageError[0].message,
            variant: 'error',
          
          }),
        );
        console.log("error", JSON.stringify(this.error));
      });
      console.log(event.target.dataset.id) 
    }
   }

This is how it looks:

enter image description here

From the debug console:

enter image description here

Any kind would be appreciated..

1 Answer 1

0

You need to change column declaration like this

const columns = [
  { label : 'FileName', fieldName : 'label'},
  {
      type : 'action',
      typeAttributes : {rowActions : actions},
  },
]; 

Instead of this.filelist you need to use "label" as in your data "filename" is stored in "label" and in "fieldname" we pass the keyname not the whole data.

10
  • 1
    Hey Thanks!! it worked.. but somehow delete button in dropdown is not working Nov 15, 2022 at 7:04
  • Instead of deleteSelectedfile({'docIds': seletedRow.Id}) pass deleteSelectedfile({'docIds': seletedRow.value}) Also in html change key-field = "value". Nov 15, 2022 at 7:08
  • no its not working.. Nov 15, 2022 at 7:13
  • Update the code here and let me check Nov 15, 2022 at 7:15
  • 1
    hey i got my mistake.. I was using onrowselection={handleRowAction} in html file instead i should have used onrowaction={handleRowAction}, this worked for me... Thanks for ur help. Nov 15, 2022 at 10:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .