function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
jaishrijaishri 

Refreshapex is not working

<template>
    <div class="slds-p-around_medium lgc-bg">
        <lightning-input type="Currency" label="AnnualRevenue Start" value={revenueStart} name="AVStart"
            onchange={handleChange}></lightning-input>
    </div>

    <div class="slds-p-around_medium lgc-bg">
        <lightning-input type="Currency" label="AnnualRevenue End" value={revenueEnd} name="AVEnd"
            onchange={handleChange}> </lightning-input>

    </div>

    <div class="slds-p-around_medium lgc-bg">
        <template if:true={typeValues.data}>
            <lightning-combobox name="Type" label="Type" value={value} options={typeValues.data.values}
                onchange={handleChange}>
            </lightning-combobox>
        </template>
    </div>

    <div class="slds-p-around_medium lgc-bg">
        <template if:true={ratingValues.data}>
            <lightning-combobox name="Rating" label="Rating" value={value} options={ratingValues.data.values}
                onchange={handleChange}>
            </lightning-combobox>
        </template>
    </div>

    <div class="slds-p-around_medium lgc-bg">
        <template if:true={industryValues.data}>
            <lightning-combobox name="Industry" label="Industry" value={value} options={industryValues.data.values}
                onchange={handleChange}>
            </lightning-combobox>
        </template>
    </div>

    <lightning-button type="submit" variant="brand" label="Show Accounts" onclick={handleClick}></lightning-button>
    
    <template if:true={showSearchComponent}>
        <lightning-datatable key-field="Id" data={accounts} columns={columns} onsave={handleSave}
            draft-values={draftValues} hide-checkbox-column="true"></lightning-datatable>
    </template>

    <template if:false={accounts}>
        <p>No data to display</p>
    </template>

    <template if:true={loading}>
        <div class="slds-spinner_container">
            <lightning-spinner alternative-text="Loading" variant="brand" size="medium">
            </lightning-spinner>
        </div>
    </template>
</template>
 
import { LightningElement, wire, track, api } from 'lwc';

import { getPicklistValues } from 'lightning/uiObjectInfoApi';
import Type from '@salesforce/schema/Account.Type';
import Rating from '@salesforce/schema/Account.Rating';
import AnnualRevenue from '@salesforce/schema/Account.AnnualRevenue';

// import ChangeRating__c from '@salesforce/schema/Account.ChangeRating__c';

import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import Industry from '@salesforce/schema/Account.Industry';

import getAccountList from '@salesforce/apex/AccountForm.getAccountList';

//import getAccounts from '@salesforce/apex/AccountForm.getAccounts';
import { updateRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { refreshApex } from '@salesforce/apex';

const columns = [
  { label: 'Account Name', fieldName: 'AccName', type: 'url', typeAttributes: { label: { fieldName: 'Name' } } },
  { label: 'AnnualRevenue', fieldName: 'AnnualRevenue', type: 'currency', editable: true },
  { label: 'Industry', fieldName: 'Industry' },
  { label: 'Type', fieldName: 'Type', editable: true },
  { label: 'Rating', fieldName: 'Rating', type: 'picklist', editable: true },
  { label: 'Website', fieldName: 'Website', type: 'url', editable: true },
  { label: 'ChangeRating', fieldName: 'ChangeRating__c', type: 'number', editable: true }
];

export default class AccountForm extends LightningElement {

  @track accounts;
  @track showSearchComponent = false;
  @track loading = false;
  @track revenueStart;
  @track revenueEnd;
  @api recordId;
  columns = columns;
  draftValues = [];
  accounts ;

  error;
  empty = false;


  @wire(getObjectInfo, { objectApiName: ACCOUNT_OBJECT })
  accountInfo;
  nameVal;
  typeVal;
  industryVal;


  @wire(getPicklistValues, { recordTypeId: '$accountInfo.data.defaultRecordTypeId', fieldApiName: Type })
  typeValues;

  @wire(getPicklistValues, { recordTypeId: '$accountInfo.data.defaultRecordTypeId', fieldApiName: Rating })
  ratingValues;

  @wire(getPicklistValues, { recordTypeId: '$accountInfo.data.defaultRecordTypeId', fieldApiName: Industry })
  industryValues;


  handleChange(event) {
    var fieldname = event.target.label;
    if (fieldname == 'Rating') {
      this.nameVal = event.target.value;
    } else if (fieldname == 'Type') {
      this.typeVal = event.target.value;
    } else if (fieldname == 'Industry') {
      this.industryVal = event.target.value;
    } else if (fieldname == 'AnnualRevenue Start') {
      this.revenueStart = event.target.value;
    } else if (fieldname == 'AnnualRevenue End') {
      this.revenueEnd = event.target.value;
    }
  }

  handleClick() {
    // console.log('buttom clicked');
    this.showSearchComponent = true;
    this.loading = true;
    //console.log('type--> '+this.typeVal+' rating--> '+this.nameVal+' industry--> '+this.industryVal);
    getAccountList({ type: this.typeVal, rating: this.nameVal, industry: this.industryVal, AnnualRevenueStart: this.revenueStart, AnnualRevenueEnd: this.revenueEnd })
      .then(results => {
        // console.log('account result--> '+JSON.stringify(result))
        let tempAccList = [];

        results.forEach((result) => {
          let tempAccRec = Object.assign({}, result);
          tempAccRec.AccName = '/' + tempAccRec.Id;
          tempAccList.push(tempAccRec);

        });
            this.accounts = tempAccList
        //  this.accounts=result;
            this.loading = false;
      })
      .catch(error => {
        console.log('error' + error);
        this.loading = false;
      })


  }


  handleSave(event) {
    const recordInputs = event.detail.draftValues.slice().map(draft => {
      const fields = Object.assign({}, draft);
      return { fields };
    });

    const promises = recordInputs.map(recordInput => updateRecord(recordInput));
    Promise.all(promises).then(accounts => {
      this.dispatchEvent(
        new ShowToastEvent({
          title: 'Success',
          message: 'Accounts updated',
          variant: 'success'
        })

      );
      // Clear all draft values
      this.draftValues = [];

      // Display fresh data in the datatable
      return refreshApex(this.accounts);
    }).catch(error => {
      // Handle error
    });
  }

public with sharing class AccountForm {
    @AuraEnabled
    public static List<Account>  getAccountList(String type,String rating,String industry,Integer AnnualRevenueStart,Integer AnnualRevenueEnd){
        String accQuery = 'SELECT Id,Name,Type,Rating,AnnualRevenue FROM Account';                     
        String whereClause  = '';
        
     /*   if(AnnualRevenueStart>=30000){
            whereClause =whereClause +' where AnnualRevenue>=30000';
        }
       if(AnnualRevenueEnd<=100000){
            whereClause =whereClause +' AND AnnualRevenue<=100000';
            
        }*/

        if(AnnualRevenueStart!=Null){
            whereClause=whereClause+' where AnnualRevenue>=:AnnualRevenueStart';
        }
        if(AnnualRevenueEnd!=Null){
            if(String.isEmpty(whereClause)){
            whereClause=whereClause+' WHERE AnnualRevenue<=:AnnualRevenueEnd';
        }
        else 
            {
                whereClause=whereClause+' AND AnnualRevenue<=:AnnualRevenueEnd';
            }
        }

        if(String.isNotEmpty(type)){
            if(String.isEmpty(whereClause)){
                whereClause =whereClause +  ' WHERE Type = :type';
            }else{
                whereClause =whereClause + ' AND Type = :type';
            }
            
        }
        if(String.isNotEmpty(rating)){
            if(String.isEmpty(whereClause)){
                whereClause =whereClause +  ' WHERE Rating = :rating';
            }else{
                whereClause =whereClause + ' AND Rating = :rating';
            }
        } 
        if(String.isNotEmpty(industry)){
            if(String.isEmpty(whereClause)){
                whereClause =whereClause +  ' WHERE Industry = :industry';
            }else{
                whereClause =whereClause + ' AND Industry = :industry';
            }
            
        } 
        String finalquery = accQuery+whereClause;
        System.debug('finalquery='+finalquery);
        
        List<Account> acclist=Database.query(finalquery);
        
        return acclist;
        
    }
}
I have build lwc component which show datatable when i give the input in field but when i change field data in row it is also save in datatable but the data is showing after refresh the whole page after saving the field it is not updating in UI Page.....can anyone help me

 
Best Answer chosen by jaishri
Maharajan CMaharajan C
Hi Jaishri,

RefreshApex can refresh data that was fetched by using wire property. I don't think you can refresh the data fetched by using the Imperative Apex.

-https://salesforce.stackexchange.com/questions/296396/how-to-refresh-a-method-that-is-called-imperatively-and-annotated-with-cacheable (https://salesforce.stackexchange.com/questions/296396/how-to-refresh-a-method-that-is-called-imperatively-and-annotated-with-cacheable)

You can again call the imperative method for refresh like below.
 
import { LightningElement, wire, track, api } from 'lwc';

import { getPicklistValues } from 'lightning/uiObjectInfoApi';
import Type from '@salesforce/schema/Account.Type';
import Rating from '@salesforce/schema/Account.Rating';
import AnnualRevenue from '@salesforce/schema/Account.AnnualRevenue';

// import ChangeRating__c from '@salesforce/schema/Account.ChangeRating__c';

import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import Industry from '@salesforce/schema/Account.Industry';

import getAccountList from '@salesforce/apex/AccountForm.getAccountList';

//import getAccounts from '@salesforce/apex/AccountForm.getAccounts';
import { updateRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { refreshApex } from '@salesforce/apex';

const columns = [
  { label: 'Account Name', fieldName: 'AccName', type: 'url', typeAttributes: { label: { fieldName: 'Name' } } },
  { label: 'AnnualRevenue', fieldName: 'AnnualRevenue', type: 'currency', editable: true },
  { label: 'Industry', fieldName: 'Industry' },
  { label: 'Type', fieldName: 'Type', editable: true },
  { label: 'Rating', fieldName: 'Rating', type: 'picklist', editable: true },
  { label: 'Website', fieldName: 'Website', type: 'url', editable: true },
  { label: 'ChangeRating', fieldName: 'ChangeRating__c', type: 'number', editable: true }
];

export default class accountForm extends LightningElement {
  @track accounts;
  @track showSearchComponent = false;
  @track loading = false;
  @track revenueStart;
  @track revenueEnd;
  @api recordId;
  columns = columns;
  draftValues = [];
  accounts ;

  error;
  empty = false;


  @wire(getObjectInfo, { objectApiName: ACCOUNT_OBJECT })
  accountInfo;
  nameVal;
  typeVal;
  industryVal;


  @wire(getPicklistValues, { recordTypeId: '$accountInfo.data.defaultRecordTypeId', fieldApiName: Type })
  typeValues;

  @wire(getPicklistValues, { recordTypeId: '$accountInfo.data.defaultRecordTypeId', fieldApiName: Rating })
  ratingValues;

  @wire(getPicklistValues, { recordTypeId: '$accountInfo.data.defaultRecordTypeId', fieldApiName: Industry })
  industryValues;


  handleChange(event) {
    var fieldname = event.target.label;
    if (fieldname == 'Rating') {
      this.nameVal = event.target.value;
    } else if (fieldname == 'Type') {
      this.typeVal = event.target.value;
    } else if (fieldname == 'Industry') {
      this.industryVal = event.target.value;
    } else if (fieldname == 'AnnualRevenue Start') {
      this.revenueStart = event.target.value;
    } else if (fieldname == 'AnnualRevenue End') {
      this.revenueEnd = event.target.value;
    }
  }

  handleClick() {
    console.log('buttom clicked 1');
    this.showSearchComponent = true;
    this.loading = true;
    console.log('type--> '+this.typeVal+' rating--> '+this.nameVal+' industry--> '+this.industryVal);
    getAccountList({ type: this.typeVal, rating: this.nameVal, industry: this.industryVal, AnnualRevenueStart: this.revenueStart, AnnualRevenueEnd: this.revenueEnd })
      .then(results => {
        // console.log('account result--> '+JSON.stringify(result))
        let tempAccList = [];
        
        results.forEach((result) => {
          let tempAccRec = Object.assign({}, result);
          tempAccRec.AccName = '/' + tempAccRec.Id;
          tempAccList.push(tempAccRec);

        });
            this.accounts = tempAccList
            this.wiredDataResult = this.accounts;
        //  this.accounts=result;
            this.loading = false;
      })
      .catch(error => {
        console.log('error' + error);
        this.loading = false;
      })


  }


  handleSave(event) {
    const recordInputs = event.detail.draftValues.slice().map(draft => {
      const fields = Object.assign({}, draft);
      return { fields };
    });

    const promises = recordInputs.map(recordInput => updateRecord(recordInput));
    Promise.all(promises).then(accounts => {
      this.dispatchEvent(
        new ShowToastEvent({
          title: 'Success',
          message: 'Accounts updated',
          variant: 'success'
        })

      );
      // Clear all draft values
      this.draftValues = [];
      this.handleClick();  // again call the imp method
      // Display fresh data in the datatable
      //return refreshApex(this.accounts);
    }).catch(error => {
      // Handle error
    });
  }
}


Update you SOQL also:
 
String accQuery = 'SELECT Id,Name,Type,Rating,AnnualRevenue,Industry,Website,ChangeRating__c FROM Account';

Thanks,
Maharajan.C

All Answers

Maharajan CMaharajan C
Hi Jaishri,

RefreshApex can refresh data that was fetched by using wire property. I don't think you can refresh the data fetched by using the Imperative Apex.

-https://salesforce.stackexchange.com/questions/296396/how-to-refresh-a-method-that-is-called-imperatively-and-annotated-with-cacheable (https://salesforce.stackexchange.com/questions/296396/how-to-refresh-a-method-that-is-called-imperatively-and-annotated-with-cacheable)

You can again call the imperative method for refresh like below.
 
import { LightningElement, wire, track, api } from 'lwc';

import { getPicklistValues } from 'lightning/uiObjectInfoApi';
import Type from '@salesforce/schema/Account.Type';
import Rating from '@salesforce/schema/Account.Rating';
import AnnualRevenue from '@salesforce/schema/Account.AnnualRevenue';

// import ChangeRating__c from '@salesforce/schema/Account.ChangeRating__c';

import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import Industry from '@salesforce/schema/Account.Industry';

import getAccountList from '@salesforce/apex/AccountForm.getAccountList';

//import getAccounts from '@salesforce/apex/AccountForm.getAccounts';
import { updateRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { refreshApex } from '@salesforce/apex';

const columns = [
  { label: 'Account Name', fieldName: 'AccName', type: 'url', typeAttributes: { label: { fieldName: 'Name' } } },
  { label: 'AnnualRevenue', fieldName: 'AnnualRevenue', type: 'currency', editable: true },
  { label: 'Industry', fieldName: 'Industry' },
  { label: 'Type', fieldName: 'Type', editable: true },
  { label: 'Rating', fieldName: 'Rating', type: 'picklist', editable: true },
  { label: 'Website', fieldName: 'Website', type: 'url', editable: true },
  { label: 'ChangeRating', fieldName: 'ChangeRating__c', type: 'number', editable: true }
];

export default class accountForm extends LightningElement {
  @track accounts;
  @track showSearchComponent = false;
  @track loading = false;
  @track revenueStart;
  @track revenueEnd;
  @api recordId;
  columns = columns;
  draftValues = [];
  accounts ;

  error;
  empty = false;


  @wire(getObjectInfo, { objectApiName: ACCOUNT_OBJECT })
  accountInfo;
  nameVal;
  typeVal;
  industryVal;


  @wire(getPicklistValues, { recordTypeId: '$accountInfo.data.defaultRecordTypeId', fieldApiName: Type })
  typeValues;

  @wire(getPicklistValues, { recordTypeId: '$accountInfo.data.defaultRecordTypeId', fieldApiName: Rating })
  ratingValues;

  @wire(getPicklistValues, { recordTypeId: '$accountInfo.data.defaultRecordTypeId', fieldApiName: Industry })
  industryValues;


  handleChange(event) {
    var fieldname = event.target.label;
    if (fieldname == 'Rating') {
      this.nameVal = event.target.value;
    } else if (fieldname == 'Type') {
      this.typeVal = event.target.value;
    } else if (fieldname == 'Industry') {
      this.industryVal = event.target.value;
    } else if (fieldname == 'AnnualRevenue Start') {
      this.revenueStart = event.target.value;
    } else if (fieldname == 'AnnualRevenue End') {
      this.revenueEnd = event.target.value;
    }
  }

  handleClick() {
    console.log('buttom clicked 1');
    this.showSearchComponent = true;
    this.loading = true;
    console.log('type--> '+this.typeVal+' rating--> '+this.nameVal+' industry--> '+this.industryVal);
    getAccountList({ type: this.typeVal, rating: this.nameVal, industry: this.industryVal, AnnualRevenueStart: this.revenueStart, AnnualRevenueEnd: this.revenueEnd })
      .then(results => {
        // console.log('account result--> '+JSON.stringify(result))
        let tempAccList = [];
        
        results.forEach((result) => {
          let tempAccRec = Object.assign({}, result);
          tempAccRec.AccName = '/' + tempAccRec.Id;
          tempAccList.push(tempAccRec);

        });
            this.accounts = tempAccList
            this.wiredDataResult = this.accounts;
        //  this.accounts=result;
            this.loading = false;
      })
      .catch(error => {
        console.log('error' + error);
        this.loading = false;
      })


  }


  handleSave(event) {
    const recordInputs = event.detail.draftValues.slice().map(draft => {
      const fields = Object.assign({}, draft);
      return { fields };
    });

    const promises = recordInputs.map(recordInput => updateRecord(recordInput));
    Promise.all(promises).then(accounts => {
      this.dispatchEvent(
        new ShowToastEvent({
          title: 'Success',
          message: 'Accounts updated',
          variant: 'success'
        })

      );
      // Clear all draft values
      this.draftValues = [];
      this.handleClick();  // again call the imp method
      // Display fresh data in the datatable
      //return refreshApex(this.accounts);
    }).catch(error => {
      // Handle error
    });
  }
}


Update you SOQL also:
 
String accQuery = 'SELECT Id,Name,Type,Rating,AnnualRevenue,Industry,Website,ChangeRating__c FROM Account';

Thanks,
Maharajan.C
This was selected as the best answer
jaishrijaishri
Hi Maharajan.C,  Thanks I have one more issue like if there is no records in datatable it is show no data display i was try but it is not working if you know please tell me
 
Maharajan CMaharajan C
Please explain little bit more... am not able to understand what you are looking...