Когда я создаю, редактирую и удаляю, список записей не обновляется по умолчанию, но все эти функции работают.

import {LightningElement, track, wire} from 'lwc';

// importing apex class methods
import getContacts from '@salesforce/apex/LWCExampleController.getContacts';
import delSelectedCons from '@salesforce/apex/LWCExampleController.deleteContacts';

// importing to show toast notifictions
import {ShowToastEvent} from 'lightning/platformShowToastEvent';

// importing to refresh the apex if any record changes the datas
import {refreshApex} from '@salesforce/apex';

import retrieveRawData from '@salesforce/apex/LWCExampleController.retrieveRawData';

// row actions
const actions = [
    { label: 'Record Details', name: 'record_details'}, 
    { label: 'Edit', name: 'edit'}, 
    { label: 'Delete', name: 'delete'}
];

// datatable columns with row actions
const columns = [
    { label: 'Name', fieldName: 'Name' }, 
   { label: 'Salary', fieldName: 'Salary__c' }, 
    {
        type: 'action',
        typeAttributes: {
            rowActions: actions,
            menuAlignment: 'right'
        }
    }
];
let i=0;

export default class RawDataTable extends LightningElement { 
    // reactive variable
    @track data;
    @track columns = columns;
    @track record = [];
    @track bShowModal = false;
    @track currentRecordId;
    @track isEditForm = false;
    @track isNewForm  = false;
    @track showLoadingSpinner = false;

    @track page = 1; //this will initialize 1st page
    @track items = []; //it contains all the records.
    //@track data = []; //data to be display in the table
    //@track columns; //holds column info.
    @track startingRecord = 1; //start record position per page
    @track endingRecord = 0; //end record position per page
    @track pageSize = 5; //default value we are assigning
    @track totalRecountCount = 0; //total record count received from all retrieved records
    @track totalPage = 0; //total number of page is needed to display all records


    // non-reactive variables
    selectedRecords = [];
    refreshTable;
    error;

    
    handleRowActions(event) {
        let actionName = event.detail.action.name;

        window.console.log('actionName ====> ' + actionName);

        let row = event.detail.row;

        window.console.log('row ====> ' + row);
        // eslint-disable-next-line default-case
        switch (actionName) {
            case 'record_details':
                this.viewCurrentRecord(row);
                break;
            case 'edit':
                this.editCurrentRecord(row);
                break;
            case 'delete':
                this.deleteCons(row);
                break;
        }
    }

    // view the current record details
    viewCurrentRecord(currentRow) {
        this.bShowModal = true;
        this.isEditForm = false;
        this.record = currentRow;
    }

    // closing modal box
    closeModal() {
        this.bShowModal = false;
    }


    editCurrentRecord(currentRow) {
        // open modal box
        this.bShowModal = true;
        this.isEditForm = true;
        this.isNewForm = false;

        // assign record id to the record edit form
        this.currentRecordId = currentRow.Id;
    }

    handleNewModal(){
        this.bShowModal = true;
        this.isNewForm = true;
        this.isEditForm = false;
    }

    // handleing record edit form submit
    handleSubmit(event) {
        // prevending default type sumbit of record edit form
        event.preventDefault();

        // querying the record edit form and submiting fields to form
        this.template.querySelector('lightning-record-edit-form').submit(event.detail.fields);

        // closing modal
        this.bShowModal = false;

        // showing success message
        this.dispatchEvent(new ShowToastEvent({
            title: 'Success!!',
            message: event.detail.fields.FirstName + ' '+ event.detail.fields.LastName +' Contact updated Successfully!!.',
            variant: 'success'
        }),);

    }

    // refreshing the datatable after record edit form success
    handleSuccess() {
        //return refreshApex(this.refreshTable);
        return refreshApex(this.refreshLWCTable);
    }

    deleteCons(currentRow) {
        let currentRecord = [];
        currentRecord.push(currentRow.Id);
        this.showLoadingSpinner = true;

        // calling apex class method to delete the selected contact
        delSelectedCons({lstConIds: currentRecord})
        .then(result => {
            window.console.log('result ====> ' + result);
            this.showLoadingSpinner = false;

            // showing success message
            this.dispatchEvent(new ShowToastEvent({
                title: 'Success!!',
                message: currentRow.FirstName + ' '+ currentRow.LastName +' Contact deleted.',
                variant: 'success'
            }),);

            // refreshing table data using refresh apex
             //return refreshApex(this.refreshTable);
             return refreshApex(this.refreshLWCTable);

        })
        .catch(error => {
            window.console.log('Error ====> '+error);
            this.dispatchEvent(new ShowToastEvent({
                title: 'Error!!', 
                message: error.message, 
                variant: 'error'
            }),);
        });
    }

    refreshLWCTable;
    @wire(retrieveRawData)
    wiredRawData({ error, data }) {
        
        if (data) {
            //if you want to perform data transformation then following code will be used,
            //so that individual values to be assigned into each columns
            
            for(i=0; i<data.length; i++) {

                this.items = [...this.items,
                                    {Id:data[i].Id, 
                                    Name:data[i].Name, 
                                    
                                    Salary__c:data[i].Salary__c}];  
            }
            
            this.items = data;
            this.totalRecountCount = data.length; //here it is 23
            this.totalPage = Math.ceil(this.totalRecountCount / this.pageSize); //here it is 5
            
            //initial data to be displayed ----------->
            //slice will take 0th element and ends with 5, but it doesn't include 5th element
            //so 0 to 4th rows will be display in the table
            
            this.data = this.items.slice(0,this.pageSize); 
            this.endingRecord = this.pageSize;
            this.columns = columns;

            this.error = undefined;
        } 
        return refreshApex(this.refreshTable);
       /* else if (error) {
            this.error = error;
            this.data = undefined;
        }*/
    }

    //clicking on previous button this method will be called
    previousHandler() {
        if (this.page > 1) {
            this.page = this.page - 1; //decrease page by 1
            this.displayRecordPerPage(this.page);
        }
    }

    //clicking on next button this method will be called
    nextHandler() {
        if((this.page<this.totalPage) && this.page !== this.totalPage){
            this.page = this.page + 1; //increase page by 1
            this.displayRecordPerPage(this.page);            
        }             
    }

    //this method displays records page by page
    displayRecordPerPage(page){

        /*let's say for 2nd page, it will be => "Displaying 6 to 10 of 23 records. Page 2 of 5"
        page = 2; pageSize = 5; startingRecord = 5, endingRecord = 10
        so, slice(5,10) will give 5th to 9th records.
        */
        this.startingRecord = ((page -1) * this.pageSize) ;
        this.endingRecord = (this.pageSize * page);

        this.endingRecord = (this.endingRecord > this.totalRecountCount) 
                            ? this.totalRecountCount : this.endingRecord; 

        this.data = this.items.slice(this.startingRecord, this.endingRecord);

        //increment by 1 to display the startingRecord count, 
        //so for 2nd page, it will show "Displaying 6 to 10 of 23 records. Page 2 of 5"
        this.startingRecord = this.startingRecord + 1;
    }    

}

<template>
    <lightning-card title="Datatable with Row Actions" icon-name="standard:contact" > <br/>

        <lightning-button label="New" variant="Neutral" title="New" onclick={handleNewModal} 
        icon-name="action:new" class="slds-m-left_x-small" ></lightning-button>

        
        

       <div style="width: auto;">
           <template if:true={data}>

               <lightning-datatable data={data}
                                    columns={columns}
                                    key-field="id"
                                    hide-checkbox-column="true"
                                    onrowaction={handleRowActions}></lightning-datatable>
           </template>

           <div class="slds-m-around_medium">
            <p class="slds-m-vertical_medium content">
                     Displaying {startingRecord} to {endingRecord} of {totalRecountCount} records.
                     Page {page} of {totalPage}. </p>
            <c-paginator onprevious={previousHandler} onnext={nextHandler}></c-paginator>
        </div>

       </div>

       <!-- Spinner -->
       <div if:true={showLoadingSpinner}>
           <lightning-spinner alternative-text="Loading" size="large"></lightning-spinner>
       </div>

       <!-- Detail view modal -->
       <template if:true={bShowModal}>
           <section role="dialog" tabindex="-1"
                   aria-labelledby="modal-heading-01"
                   aria-modal="true"
                   aria-describedby="modal-content-id-1"
                   class="slds-modal slds-fade-in-open">
           <div class="slds-modal__container">


            
               <!-- modal header -->
               <header class="slds-modal__header">
                   <button class="slds-button slds-button_icon slds-modal__close slds-button_icon-inverse" title="Close" onclick={closeModal}>
                       <lightning-icon icon-name="utility:close" alternative-text="close" variant="inverse" size="small" ></lightning-icon>
                   </button>
                   
                   <h2 id="modal-heading-01" class="slds-text-heading_medium slds-hyphenate" if:false={isEditForm}>Record</h2>
                   <h2 id="modal-heading-02" class="slds-text-heading_medium slds-hyphenate" if:true={isEditForm}>Update Record Values</h2>
               </header>
               <!-- modal body -->
               <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1" if:false={isNewForm}>
                   <dl class="slds-list_horizontal slds-wrap">
                       <dt class="slds-item_label slds-truncate" title="Name">Name:</dt>
                       <dd class="slds-item_detail slds-truncate">{record.Name}</dd>
                       <dt class="slds-item_label slds-truncate" title="Salary">Salary:</dt>
                       <dd class="slds-item_detail slds-truncate">{record.Salary__c}</dd>
                       
                   </dl>
               </div>
               
               <!-- showing record edit form -->
               <div if:true={isEditForm} class="slds-theme_default">
                   <lightning-record-edit-form layout-type="Full" record-id={currentRecordId} object-api-name="Raw_Data__c" onsubmit={handleSubmit} onsuccess={handleSuccess}>
                       <lightning-messages></lightning-messages>
                       <lightning-input-field field-name="Name"></lightning-input-field>
                       <lightning-input-field field-name="Salary__c"></lightning-input-field>
                       
                       
                       <div style="text-align:center;">
                           <lightning-button class="slds-m-top_small"
                                             variant="brand"
                                             type="submit"
                                             name="update"
                                             label="Update Record"></lightning-button>
                       </div>
                   </lightning-record-edit-form><br/>
                   <div></div>
               </div>

               <div if:true={isNewForm} class="slds-theme_default">
                <lightning-record-edit-form layout-type="Full" object-api-name="Raw_Data__c" onsubmit={handleSubmit} onsuccess={handleSuccess}>
                    <lightning-messages></lightning-messages>
                    <lightning-input-field field-name="Name"></lightning-input-field>
                    <lightning-input-field field-name="Salary__c"></lightning-input-field>
                    
                    
                    <div style="text-align:center;">
                        <lightning-button class="slds-m-top_small"
                                          variant="brand"
                                          type="submit"
                                          name="save"
                                          label="Save"></lightning-button>
                    </div>
                </lightning-record-edit-form><br/>
                <div></div>
            </div>
               
               <!-- modal footer start-->
               <footer class="slds-modal__footer" if:false={isEditForm}>
                   <lightning-button variant="brand"
                                     label="Close"
                                     title="Close"
                                     onclick={closeModal}></lightning-button>
               </footer>
           </div>
           </section>
           <div class="slds-backdrop slds-backdrop_open"></div>

           
          
       </template>
   </lightning-card>   
</template>

public inherited sharing class LWCExampleController {
    
    
    
    @AuraEnabled
    public static void deleteContacts(list<Id> lstConIds){
        try {
            list<Raw_Data__c> lstConsToDelete = new list<Raw_Data__c>();
            System.debug('lstConIds ====> '+lstConIds);
            for(Id idCon : lstConIds) {
                lstConsToDelete.add(new Raw_Data__c(Id = idCon));
            }
            if(!lstConsToDelete.isEmpty()) {
                delete lstConsToDelete;
            }
        }
        catch(Exception ex) {
            throw new AuraHandledException(ex.getMessage());
        }
    }

    @AuraEnabled (cacheable=true)
    public static List<Raw_Data__c> retrieveRawData(){
        return [SELECT Id, Name, Salary__c FROM Raw_Data__c
                LIMIT 1000];
    }
}
0
sfdcfox 15 Июл 2020 в 21:32

1 ответ

Лучший ответ

Вам необходимо обновить фактические данные проводов, чтобы они заработали. Минимальное изменение, которое вы должны сделать здесь:

refreshLWCTable;
@wire(retrieveRawData)
wiredRawData(response) {
  this.refreshLWCTable = response;
  let { data, error } = response;
0
sfdcfox 15 Июл 2020 в 21:36