Salesforce学习 Lwc(十三)【InLineEdit】更新数据的三种方式

2021-01-12 10:18:19 浏览数 (1)

前边讲过如何使用【lightning-datatable】表示数据,以及一些基本样式,今天讲解在【InLineEdit】模式下,通过Lwc方法和Apex自定义方法进行编辑后的数据更新。

2.【updateRecord】

代码语言:javascript复制
<template>
  <lightning-card title="Datatable Example" icon-name="custom:custom63">
      <div class="slds-m-around_medium">
          <template if:true={contact.data}>
              <lightning-datatable
                  key-field="Id"
                  data={contact.data}
                  columns={columns}
                  onsave={handleSave}
                  draft-values={draftValues}>
              </lightning-datatable>
          </template>
          <template if:true={contact.error}>
              <!-- handle Apex error -->
          </template>
      </div>
  </lightning-card>
</template>
代码语言:javascript复制
import { LightningElement, wire, api } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
import { refreshApex } from '@salesforce/apex';
import { updateRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import FIRSTNAME_FIELD from '@salesforce/schema/Contact.FirstName';
import LASTNAME_FIELD from '@salesforce/schema/Contact.LastName';
import ID_FIELD from '@salesforce/schema/Contact.Id';
const COLS = [
    { label: 'First Name', fieldName: 'FirstName', editable: true },
    { label: 'Last Name', fieldName: 'LastName', editable: true },
    { label: 'Title', fieldName: 'Title' },
    { label: 'Phone', fieldName: 'Phone', type: 'phone' },
    { label: 'Email', fieldName: 'Email', type: 'email' }
];
export default class ApexContactsForAccount extends LightningElement {
    @api recordId;
    columns = COLS;
    draftValues = [];

    @wire(getContacts, { accId: '$recordId' })
    contact;

    handleSave(event) {
        const fields = {};
        fields[ID_FIELD.fieldApiName] = event.detail.draftValues[0].Id;
        fields[FIRSTNAME_FIELD.fieldApiName] = event.detail.draftValues[0].FirstName;
        fields[LASTNAME_FIELD.fieldApiName] = event.detail.draftValues[0].LastName;
        const recordInput = {fields};
        updateRecord(recordInput)
        .then(() => {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Success',
                    message: 'Contact updated',
                    variant: 'success'
                })
            );
            // Display fresh data in the datatable
            return refreshApex(this.contact).then(() => {
                // Clear all draft values in the datatable
                this.draftValues = [];

            });
        }).catch(error => {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error updating or reloading record',
                    message: error.body.message,
                    variant: 'error'
                })
            );
        });
    }
}
代码语言:javascript复制
public with sharing class ContactController {
    @AuraEnabled(cacheable=true)
    public static List<Contact> getContacts(String accId) {
        return [
            SELECT AccountId, Id, FirstName, LastName, Title, Phone, Email
            FROM Contact
            WHERE AccountId = :accId
            WITH SECURITY_ENFORCED
        ];
    }
}

效果展示:↓↓↓

编辑后效果:↓↓↓

更新后效果:↓↓↓

2.【event.detail.draftValues】 【updateRecord】

使用【event.detail.draftValues】方法可以取得编辑后的值和RecordId,在利用【updateRecord】方法进行数据更新

代码语言:javascript复制
<template>
  <lightning-card title="Datatable Example1" icon-name="custom:custom63">
      <div class="slds-m-around_medium">
          <template if:true={contact.data}>
              <lightning-datatable
                  key-field="Id"
                  data={contact.data}
                  columns={columns}
                  onsave={handleSave}
                  draft-values={draftValues}>
              </lightning-datatable>
          </template>
          <template if:true={contact.error}>
              <!-- handle Apex error -->
          </template>
      </div>
  </lightning-card>
</template>
代码语言:javascript复制
import { LightningElement, wire, api } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
import { refreshApex } from '@salesforce/apex';
import { updateRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

const COLS = [
    { label: 'First Name', fieldName: 'FirstName', editable: true },
    { label: 'Last Name', fieldName: 'LastName', editable: true },
    { label: 'Title', fieldName: 'Title' },
    { label: 'Phone', fieldName: 'Phone', type: 'phone' },
    { label: 'Email', fieldName: 'Email', type: 'email' }
];

export default class ApexContactsForAccount1 extends LightningElement {
    @api recordId;
    columns = COLS;
    draftValues = [];

    @wire(getContacts, { accId: '$recordId' })
    contact;

    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(contacts => {
          this.dispatchEvent(
              new ShowToastEvent({
                  title: 'Success',
                  message: 'Contacts updated',
                  variant: 'success'
              })
          );
           // Clear all draft values
           this.draftValues = [];

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

效果展示:

编辑后效果:↓↓↓

更新后效果:↓↓↓

3.【event.detail.draftValues】 【ApexClass】

代码语言:javascript复制
<template>
  <lightning-card title="Datatable Example2" icon-name="custom:custom63">
      <div class="slds-m-around_medium">
          <template if:true={contact.data}>
              <lightning-datatable
                  key-field="Id"
                  data={contact.data}
                  columns={columns}
                  onsave={handleSave}
                  draft-values={draftValues}>
              </lightning-datatable>
          </template>
          <template if:true={contact.error}>
              <!-- handle Apex error -->
          </template>
      </div>
  </lightning-card>
</template>
代码语言:javascript复制
import { LightningElement, wire, api } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
import { refreshApex } from '@salesforce/apex';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import updateContacts from '@salesforce/apex/ContactController.updateContacts';
import { getRecordNotifyChange } from 'lightning/uiRecordApi';
const COLS = [
    { label: 'First Name', fieldName: 'FirstName', editable: true },
    { label: 'Last Name', fieldName: 'LastName', editable: true },
    { label: 'Title', fieldName: 'Title' },
    { label: 'Phone', fieldName: 'Phone', type: 'phone' },
    { label: 'Email', fieldName: 'Email', type: 'email' }
];

export default class ApexContactsForAccount2 extends LightningElement {
    @api recordId;
    columns = COLS;
    draftValues = [];

    @wire(getContacts, { accId: '$recordId' })
    contact;

    async handleSave(event) {
      const updatedFields = event.detail.draftValues;

      // Prepare the record IDs for getRecordNotifyChange()
      const notifyChangeIds = updatedFields.map(row => { return { "recordId": row.Id } });

     // Pass edited fields to the updateContacts Apex controller
      await updateContacts({data: updatedFields})
      .then(result => {
          console.log(JSON.stringify("Apex update result: "  result));
          this.dispatchEvent(
              new ShowToastEvent({
                  title: 'Success',
                  message: 'Contact updated',
                  variant: 'success'
              })
          );

      // Refresh LDS cache and wires
      getRecordNotifyChange(notifyChangeIds);

      // Display fresh data in the datatable
      refreshApex(this.contact).then(() => {
          // Clear all draft values in the datatable
          this.draftValues = [];
        });


     }).catch(error => {
         this.dispatchEvent(
              new ShowToastEvent({
                  title: 'Error updating or refreshing records',
                  message: error.body.message,
                  variant: 'error'
              })
          );
      });
  }
}
代码语言:javascript复制
public with sharing class ContactController {
    @AuraEnabled(cacheable=true)
    public static List<Contact> getContacts(String accId) {
        return [
            SELECT AccountId, Id, FirstName, LastName, Title, Phone, Email
            FROM Contact
            WHERE AccountId = :accId
            WITH SECURITY_ENFORCED
        ];
    }
    @AuraEnabled
    public static string updateContacts(Object data) {
        List<Contact> contactsForUpdate
            = (List<Contact>) JSON.deserialize(JSON.serialize(data), List<Contact>.class);
        try {
            update contactsForUpdate;
            return 'Success: contacts updated successfully';
        }
        catch (Exception e) {
            return 'The following exception has occurred: '   e.getMessage();
        }
    }
}

效果展示:

编辑后效果:↓↓↓

更新后效果:↓↓↓

0 人点赞