Salesforce学习 Lwc(九)【数据初期取得与更新】运用详解

2020-12-30 11:08:26 浏览数 (1)

开发自定义画面经常遇到的场景就是增删改查,关于数据更新用到的几个方法进行一下总结,常用到的有以下几种。

·【lightning-record-edit-form】 【lightning-input-field】

※数据初期化和数据更新用标签自带功能,不用特殊处理,相对简单,但也有一些限制。

·【lightning-record-form】 【lightning-input】 【getRecord】 【updateRecord】

※方法1如果有限制,就可以用这个方法,比如Event/Task不支持方法1

·【lightning-record-form】 【lightning-input】 【getRecord】 Apex代码(数据更新)

※方法2如果有限制,就可以用这个方法,比如要更新的项目,当前用户没有权限。

·【lightning-record-form】 【lightning-input】 Apex代码(数据取得) Apex代码(数据更新)

※方法2如果有限制,就可以用这个方法,比如画面需要表示的项目是关联表的情况下,用Apex代码一次取得所有项目。

例1:【lightning-record-edit-form】 【lightning-input-field】

dreamHouseOpportunityEditForm1.html

代码语言:javascript复制
<template>
    <lightning-card>
        <lightning-record-edit-form record-id={recordId} object-api-name={objectApiName}
            onsubmit={handleSubmit} onsuccess={handleSuccess} onerror={handleError}>
            <lightning-messages>
            </lightning-messages>
                <lightning-layout multiple-rows="true">
                    <lightning-layout-item  padding="around-small" flexibility='auto' size='6'>
                        <lightning-input-field field-name="Name" variant="label-stacked"></lightning-input-field>
                    </lightning-layout-item>
                    <lightning-layout-item  padding="around-small" flexibility='auto' size='6'>
                        <lightning-input-field field-name="AccountId" variant="label-stacked"></lightning-input-field>
                    </lightning-layout-item>
                    <lightning-layout-item  padding="around-small" flexibility='auto' size='6'>
                        <lightning-input-field field-name="StageName" variant="label-stacked"></lightning-input-field>
                    </lightning-layout-item>
                    <lightning-layout-item  padding="around-small" flexibility='auto' size='6'>
                        <lightning-input-field field-name="OwnerId" variant="label-stacked"></lightning-input-field>
                    </lightning-layout-item>
                    <lightning-layout-item  padding="around-small" flexibility='auto' size='6'>
                        <lightning-input-field field-name="IsPrivate" variant="label-stacked"></lightning-input-field>
                    </lightning-layout-item>
                    <lightning-layout-item  padding="around-small" flexibility='auto' size='6'>
                        <lightning-input-field field-name="CloseDate" variant="label-stacked"></lightning-input-field>
                    </lightning-layout-item>
                </lightning-layout>
            <lightning-layout-item size="12">
                <div class="slds-m-top_medium">
                    <lightning-button class="slds-m-top_small" label="Cancel"
                    onclick={handleReset}></lightning-button>
                    <lightning-button class="slds-m-top_small" type="submit"
                    label="Save Record"  onclick={handleClick}></lightning-button>
                </div>
            </lightning-layout-item>
        </lightning-record-edit-form>
    </lightning-card>
</template>

dreamHouseOpportunityEditForm1.js

代码语言:javascript复制
import { LightningElement, api, track, wire } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { NavigationMixin } from 'lightning/navigation';

export default class DreamHouseOpportunityEditForm1 extends NavigationMixin(LightningElement) {
    @api recordId;
    @api objectApiName;
    handleSubmit(event) {
        event.preventDefault();
        const fields = event.detail.fields;
        this.template.querySelector('lightning-record-edit-form').submit(fields);
    }
    handleSuccess() {
      const evt = new ShowToastEvent({
            title: 'Opportunity Operated Success',
            message: 'Opportunity updated',
            variant: 'success'
        });
        this.dispatchEvent(evt);
    }
    handleError(event) {
      const evt = new ShowToastEvent({
        title: "Opportunity Operated Failed",
        message: event.detail.message,
        variant: "error"
      });
      this.dispatchEvent(evt);
    }
    handleReset(event) {
        const inputFields = this.template.querySelectorAll(
            'lightning-input-field'
        );
        if (inputFields) {
            inputFields.forEach(field => {
                field.reset();
            });
        }
    }
}

效果展示:

例2:【lightning-record-form】 【lightning-input】 【getRecord】 【updateRecord】

dreamHouseOpportunityEditForm2.html

代码语言:javascript复制
<template>
  <lightning-card>
    <lightning-record-form record-id={recordId} object-api-name={objectApiName} mode="view">
    </lightning-record-form>
    <lightning-layout multiple-rows="true">
        <lightning-layout-item  padding="around-small" flexibility='auto' size='6'>
            <lightning-input name="name" value={EditForm.name} label="Opportunity Name" class="opportunityName" onchange={handleChange}></lightning-input>
        </lightning-layout-item>
        <lightning-layout-item  padding="around-small" flexibility='auto' size='6'>
            <lightning-input name="accountId" value={EditForm.accountId} label="Account Name" class="opportunityName" onchange={handleChange}></lightning-input>
        </lightning-layout-item>
        <lightning-layout-item padding="horizontal-small" flexibility='auto' size='6'>
            <label>Stage</label>
            <lightning-combobox name="stageName" variant="label-hidden"
                value={EditForm.stageName} options={optionsStageName}  class="opportunityName" onchange={handleChange}>
            </lightning-combobox>
        </lightning-layout-item>
        <lightning-layout-item  padding="around-small" flexibility='auto' size='6'>
            <lightning-input name="ownerId" type="text" value={EditForm.ownerId} label="Opportunity Owner"  class="opportunityName" onchange={handleChange}></lightning-input>
        </lightning-layout-item>
        <lightning-layout-item  padding="around-small" flexibility='auto' size='6'>
            <lightning-input name="isPrivate" type="checkBox" checked={EditForm.isPrivate} label="Private"  class="opportunityName" onchange={handleCheckChange}></lightning-input>
        </lightning-layout-item>
        <lightning-layout-item  padding="around-small" flexibility='auto' size='6'>
            <lightning-input name="closeDate" type="date" value={EditForm.closeDate} label="Close Date"  class="opportunityName" onchange={handleChange}></lightning-input>
        </lightning-layout-item>
    </lightning-layout>
    <lightning-layout-item size="12">
        <div class="slds-m-top_medium">
            <lightning-button class="slds-m-top_small" type="submit" label="Save Record"
                onclick={handleSave}>
            </lightning-button>
        </div>
    </lightning-layout-item>
  </lightning-card>
</template>

dreamHouseOpportunityEditForm2.js

代码语言:javascript复制
import { LightningElement, api, track, wire } from 'lwc';
import { updateRecord,getRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { NavigationMixin } from 'lightning/navigation';
import OPPORTUNITY_ID_FIELD from '@salesforce/schema/Opportunity.Id';
import OPPORTUNITY_NAME_FIELD from '@salesforce/schema/Opportunity.Name';
import OPPORTUNITY_OWNERID_FIELD from '@salesforce/schema/Opportunity.OwnerId';
import OPPORTUNITY_ISPRIVATE_FIELD from '@salesforce/schema/Opportunity.IsPrivate';
import OPPORTUNITY_CLOSEDATE_FIELD from '@salesforce/schema/Opportunity.CloseDate';
import OPPORTUNITY_ACCOUNTID_FIELD from '@salesforce/schema/Opportunity.AccountId';
import OPPORTUNITY_STAGENAME_FIELD from '@salesforce/schema/Opportunity.StageName';
const infoFields = [
    OPPORTUNITY_ID_FIELD,
    OPPORTUNITY_NAME_FIELD,
    OPPORTUNITY_OWNERID_FIELD,
    OPPORTUNITY_ISPRIVATE_FIELD,
    OPPORTUNITY_CLOSEDATE_FIELD,
    OPPORTUNITY_ACCOUNTID_FIELD,
    OPPORTUNITY_STAGENAME_FIELD
];
export default class DreamHouseOpportunityEditForm2 extends NavigationMixin(LightningElement) {
    @api recordId;
    @api objectApiName;
    @track opportunityRecord
    @track EditForm = {
        name:'',
        ownerId:'',
        isPrivate:'',
        closeDate:'',
        accountId:'',
        stageName:''
    }
    @track optionsStageName = [];
    async connectedCallback() {
        let optionsStageNameTempValues = [];
        optionsStageNameTempValues.push({ label: '-', value: '' });
        optionsStageNameTempValues.push({ label: '未割当', value: '未割当' });
        optionsStageNameTempValues.push({ label: '方針策定', value: '方針策定' });
        optionsStageNameTempValues.push({ label: '提案準備', value: '提案準備' });
        optionsStageNameTempValues.push({ label: '申込済・計上待ち', value: '申込済・計上待ち' });
        optionsStageNameTempValues.push({ label: '成立', value: '成立' });
        this.optionsStageName = optionsStageNameTempValues;
    }
    @wire(getRecord, { recordId: '$recordId', fields: infoFields })
    wiredOpportunity(value) {
        this.opportunityRecord = value;
        const { data, error } = value;
        if (error) {
        } else if (data && data.fields) {
            this.EditForm.name = data.fields.Name.value;
            this.EditForm.ownerId = data.fields.OwnerId.value;
            this.EditForm.isPrivate = data.fields.IsPrivate.value;
            this.EditForm.closeDate = data.fields.CloseDate.value;
            this.EditForm.accountId = data.fields.AccountId.value;
            this.EditForm.stageName = data.fields.StageName.value;
        }
    }

    handleChange(event) {
        if(event.target.name === 'ownerId') {
            this.EditForm.ownerId = event.detail.value;
        } else if(event.target.name === 'closeDate') {
            this.EditForm.closeDate = event.detail.value;
        } else if(event.target.name === 'name') {
            this.EditForm.name = event.detail.value;
        } else if(event.target.name === 'accountId') {
            this.EditForm.accountId = event.detail.value;
        } else if(event.target.name === 'stageName') {
            this.EditForm.stageName = event.detail.value;
        }
    }
    handleCheckChange(event) {
        if(event.target.name === 'isPrivate') {
            this.EditForm.isPrivate = event.detail.checked;
        }
    }
    handleSave() {
        const fields = {};
        fields[OPPORTUNITY_ID_FIELD.fieldApiName] = this.recordId;
        fields[OPPORTUNITY_NAME_FIELD.fieldApiName] = this.EditForm.name;
        fields[OPPORTUNITY_OWNERID_FIELD.fieldApiName] = this.EditForm.ownerId;
        fields[OPPORTUNITY_ISPRIVATE_FIELD.fieldApiName] = this.EditForm.isPrivate;
        fields[OPPORTUNITY_CLOSEDATE_FIELD.fieldApiName] = this.EditForm.closeDate;
        fields[OPPORTUNITY_ACCOUNTID_FIELD.fieldApiName] = this.EditForm.accountId;
        fields[OPPORTUNITY_STAGENAME_FIELD.fieldApiName] = this.EditForm.stageName;
        const recordInput = { fields };
        updateRecord(recordInput)
        .then(() => {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Success',
                    message: 'Opportunity updated',
                    variant: 'success'
                })
            );
        }).catch(error => {
            //
        });
    }
}

效果展示:

※上边【AccountName】,【OwnerId】是参照关系的项目,所以没有实现标准画面的样式,解决方法请参照我前边博客内容,这里就先不多说明了,【Salesforce学习 LWC(四)项目的label名重写】

URL地址:https://cloud.tencent.com/developer/article/1761174

例3:【lightning-record-form】 【lightning-input】 【getRecord】 Apex代码(数据更新)

dreamHouseOpportunityEditForm3.html

代码语言:javascript复制
<template>
    <lightning-card>
      <lightning-record-form record-id={recordId} object-api-name={objectApiName} mode="view">
      </lightning-record-form>
      <lightning-layout multiple-rows="true">
          <lightning-layout-item  padding="around-small" flexibility='auto' size='6'>
              <lightning-input name="name" value={EditForm.name} label="Opportunity Name" onchange={handleChange}></lightning-input>
          </lightning-layout-item>
          <lightning-layout-item  padding="around-small" flexibility='auto' size='6'>
              <lightning-input name="accountId" value={EditForm.accountId} label="Account Name" onchange={handleChange}></lightning-input>
          </lightning-layout-item>
          <lightning-layout-item padding="horizontal-small" flexibility='auto' size='6'>
              <label>Stage</label>
              <lightning-combobox name="stageName" variant="label-hidden"
                  value={EditForm.stageName} options={optionsStageName} onchange={handleChange}>
              </lightning-combobox>
          </lightning-layout-item>
          <lightning-layout-item  padding="around-small" flexibility='auto' size='6'>
              <lightning-input name="ownerId" type="text" value={EditForm.ownerId} label="Opportunity Owner" onchange={handleChange}></lightning-input>
          </lightning-layout-item>
          <lightning-layout-item  padding="around-small" flexibility='auto' size='6'>
              <lightning-input name="isPrivate" type="checkBox" checked={EditForm.isPrivate} label="Private" onchange={handleCheckChange}></lightning-input>
          </lightning-layout-item>
          <lightning-layout-item  padding="around-small" flexibility='auto' size='6'>
              <lightning-input name="closeDate" type="date" value={EditForm.closeDate} label="Close Date" onchange={handleChange}></lightning-input>
          </lightning-layout-item>
      </lightning-layout>
      <lightning-layout-item size="12">
          <div class="slds-m-top_medium">
              <lightning-button class="slds-m-top_small" type="submit" label="Save Record"
                  onclick={handleSave}>
              </lightning-button>
          </div>
      </lightning-layout-item>
    </lightning-card>
  </template>

dreamHouseOpportunityEditForm3.js

代码语言:javascript复制
import { LightningElement, api, track, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
import opportunitySaveRecord from '@salesforce/apex/opportunitySaveRecordController.opportunitySaveRecord';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import OPPORTUNITY_ID_FIELD from '@salesforce/schema/Opportunity.Id';
import OPPORTUNITY_NAME_FIELD from '@salesforce/schema/Opportunity.Name';
import OPPORTUNITY_OWNERID_FIELD from '@salesforce/schema/Opportunity.OwnerId';
import OPPORTUNITY_ISPRIVATE_FIELD from '@salesforce/schema/Opportunity.IsPrivate';
import OPPORTUNITY_CLOSEDATE_FIELD from '@salesforce/schema/Opportunity.CloseDate';
import OPPORTUNITY_ACCOUNTID_FIELD from '@salesforce/schema/Opportunity.AccountId';
import OPPORTUNITY_STAGENAME_FIELD from '@salesforce/schema/Opportunity.StageName';
const infoFields = [
    OPPORTUNITY_ID_FIELD,
    OPPORTUNITY_NAME_FIELD,
    OPPORTUNITY_OWNERID_FIELD,
    OPPORTUNITY_ISPRIVATE_FIELD,
    OPPORTUNITY_CLOSEDATE_FIELD,
    OPPORTUNITY_ACCOUNTID_FIELD,
    OPPORTUNITY_STAGENAME_FIELD
];
export default class DreamHouseOpportunityEditForm3 extends LightningElement {
  @api recordId;
    @api objectApiName;
    @track opportunityRecord
    @track EditForm = {
        id:'',
        name:'',
        ownerId:'',
        isPrivate:'',
        closeDate:'',
        accountId:'',
        stageName:''
    }
    @track optionsStageName = [];
    async connectedCallback() {
        let optionsStageNameTempValues = [];
        optionsStageNameTempValues.push({ label: '-', value: '' });
        optionsStageNameTempValues.push({ label: '未割当', value: '未割当' });
        optionsStageNameTempValues.push({ label: '方針策定', value: '方針策定' });
        optionsStageNameTempValues.push({ label: '提案準備', value: '提案準備' });
        optionsStageNameTempValues.push({ label: '申込済・計上待ち', value: '申込済・計上待ち' });
        optionsStageNameTempValues.push({ label: '成立', value: '成立' });
        this.optionsStageName = optionsStageNameTempValues;
    }
    @wire(getRecord, { recordId: '$recordId', fields: infoFields })
    wiredOpportunity(value) {
        this.opportunityRecord = value;
        const { data, error } = value;
        if (error) {
        } else if (data && data.fields) {
            this.EditForm.id = data.fields.Id.value;
            this.EditForm.name = data.fields.Name.value;
            this.EditForm.ownerId = data.fields.OwnerId.value;
            this.EditForm.isPrivate = data.fields.IsPrivate.value;
            this.EditForm.closeDate = data.fields.CloseDate.value;
            this.EditForm.accountId = data.fields.AccountId.value;
            this.EditForm.stageName = data.fields.StageName.value;
        }
    }

    handleChange(event) {
        if(event.target.name === 'ownerId') {
            this.EditForm.ownerId = event.detail.value;
        } else if(event.target.name === 'closeDate') {
            this.EditForm.closeDate = event.detail.value;
        } else if(event.target.name === 'name') {
            this.EditForm.name = event.detail.value;
        } else if(event.target.name === 'accountId') {
            this.EditForm.accountId = event.detail.value;
        } else if(event.target.name === 'stageName') {
            this.EditForm.stageName = event.detail.value;
        }
    }
    handleCheckChange(event) {
        if(event.target.name === 'isPrivate') {
            this.EditForm.isPrivate = event.detail.checked;
        }
    }
    handleSave() {
        opportunitySaveRecord({ inputOpportunity: JSON.stringify(this.EditForm) })
        .then(result => {
            console.log('result>>>>>>>>>>>'   result);
            if (result === 'success') {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Opportunity updated',
                        variant: 'success'
                    })
                );
            }
        })
        .catch(error => {
            //
        });
    }
}

opportunitySaveRecordController.cls

代码语言:javascript复制
public with sharing class opportunitySaveRecordController {
    @AuraEnabled
    public static String opportunitySaveRecord(String inputOpportunity) {
        // Opportunity opportunity =
        //     (Opportunity)JSON.deserializeStrict(inputOpportunity, Opportunity.class);
        OpportunityWrapper opportunityW =
            (OpportunityWrapper)JSON.deserializeStrict(inputOpportunity, opportunitySaveRecordController.OpportunityWrapper.class);
        system.debug('opportunityW>>>>>>>>>>>>>' opportunityW);
        Opportunity currentOpportunity = new Opportunity();
        currentOpportunity.Id = opportunityW.Id;
        currentOpportunity.Name = opportunityW.name;
        currentOpportunity.OwnerId = opportunityW.ownerId;
        currentOpportunity.IsPrivate = opportunityW.isPrivate;
        currentOpportunity.CloseDate = Date.valueOf(opportunityW.closeDate);
        currentOpportunity.AccountId = opportunityW.accountId;
        currentOpportunity.StageName = opportunityW.stageName;
        system.debug('currentOpportunity>>>>>>>>>>>>>' currentOpportunity);
        Database.SaveResult resultObj = Database.update(currentOpportunity, false);
        if (resultObj.isSuccess()){
            system.debug('更新成功>>>>>>>>>>>>>>:::::');
            return 'success';
        } else {
            system.debug('実行結果エラー>>>>>>>>::'   resultObj.getErrors());
            return 'error';
        }
    }
    public class OpportunityWrapper {
        public String id;
        public String name;
        public String ownerId;
        public Boolean isPrivate;
        public String closeDate;
        public String accountId;
        public String stageName;
    }
}

效果展示:

初期表示:↓↓↓↓

更新后状态↓↓↓↓↓↓

虽然更新成功了,但是打开别的Component,发现数据并没有刷新,这样用户体验不是特别友好。

打开其它Component↓↓↓↓↓↓

改善方法是在头部引入【refreshApex】,然后在更新成功之后进行刷新处理。

例4:【lightning-record-form】 【lightning-input】 Apex代码(数据取得) Apex代码(数据更新)

dreamHouseOpportunityEditForm4.html

代码语言:javascript复制
<template>
  <lightning-card>
    <lightning-record-form record-id={recordId} object-api-name={objectApiName} mode="view">
    </lightning-record-form>
    <lightning-layout multiple-rows="true">
        <lightning-layout-item  padding="around-small" flexibility='auto' size='6'>
            <lightning-input name="name" value={EditForm.name} label="Opportunity Name" onchange={handleChange}></lightning-input>
        </lightning-layout-item>
        <lightning-layout-item  padding="around-small" flexibility='auto' size='6'>
            <lightning-input name="accountId" value={EditForm.accountId} label="Account Name" onchange={handleChange}></lightning-input>
        </lightning-layout-item>
        <lightning-layout-item padding="horizontal-small" flexibility='auto' size='6'>
            <label>Stage</label>
            <lightning-combobox name="stageName" variant="label-hidden"
                value={EditForm.stageName} options={optionsStageName} onchange={handleChange}>
            </lightning-combobox>
        </lightning-layout-item>
        <lightning-layout-item  padding="around-small" flexibility='auto' size='6'>
            <lightning-input name="ownerId" type="text" value={EditForm.ownerId} label="Opportunity Owner" onchange={handleChange}></lightning-input>
        </lightning-layout-item>
        <lightning-layout-item  padding="around-small" flexibility='auto' size='6'>
            <lightning-input name="isPrivate" type="checkBox" checked={EditForm.isPrivate} label="Private" onchange={handleCheckChange}></lightning-input>
        </lightning-layout-item>
        <lightning-layout-item  padding="around-small" flexibility='auto' size='6'>
            <lightning-input name="closeDate" type="date" value={EditForm.closeDate} label="Close Date" onchange={handleChange}></lightning-input>
        </lightning-layout-item>
    </lightning-layout>
    <lightning-layout-item size="12">
        <div class="slds-m-top_medium">
            <lightning-button class="slds-m-top_small" type="submit" label="Save Record"
                onclick={handleSave}>
            </lightning-button>
        </div>
    </lightning-layout-item>
  </lightning-card>
</template>

dreamHouseOpportunityEditForm4.js

代码语言:javascript复制
import { LightningElement, api, track, wire } from 'lwc';
import opportunitySaveRecord from '@salesforce/apex/opportunitySaveRecordController.opportunitySaveRecord';
import getOpportunityByRecordId from '@salesforce/apex/opportunitySaveRecordController.getOpportunityByRecordId';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { refreshApex } from '@salesforce/apex';

export default class DreamHouseOpportunityEditForm4 extends LightningElement {
    @api recordId;
    @api objectApiName;
    @track opportunityRecord
    @track EditForm = {
        id:'',
        name:'',
        ownerId:'',
        isPrivate:'',
        closeDate:'',
        accountId:'',
        stageName:''
    }
    @track optionsStageName = [];
    async connectedCallback() {
        let optionsStageNameTempValues = [];
        optionsStageNameTempValues.push({ label: '-', value: '' });
        optionsStageNameTempValues.push({ label: '未割当', value: '未割当' });
        optionsStageNameTempValues.push({ label: '方針策定', value: '方針策定' });
        optionsStageNameTempValues.push({ label: '提案準備', value: '提案準備' });
        optionsStageNameTempValues.push({ label: '申込済・計上待ち', value: '申込済・計上待ち' });
        optionsStageNameTempValues.push({ label: '成立', value: '成立' });
        this.optionsStageName = optionsStageNameTempValues;
    }
    @wire(getOpportunityByRecordId, { recordId: '$recordId' })
    wiredOpportunity(value) {
        this.opportunityRecord = value;
        const { data, error } = value;
        console.log('data>>>>>>>>>>>'   JSON.stringify(data));
        if (error) {
        } else if (data) {
            this.EditForm.id = data.Id;
            this.EditForm.name = data.Name;
            this.EditForm.ownerId = data.OwnerId;
            this.EditForm.isPrivate = data.IsPrivate;
            this.EditForm.closeDate = data.CloseDate;
            this.EditForm.accountId = data.AccountId;
            this.EditForm.stageName = data.StageName;
        }
    }

    handleChange(event) {
        if(event.target.name === 'ownerId') {
            this.EditForm.ownerId = event.detail.value;
        } else if(event.target.name === 'closeDate') {
            this.EditForm.closeDate = event.detail.value;
        } else if(event.target.name === 'name') {
            this.EditForm.name = event.detail.value;
        } else if(event.target.name === 'accountId') {
            this.EditForm.accountId = event.detail.value;
        } else if(event.target.name === 'stageName') {
            this.EditForm.stageName = event.detail.value;
        }
    }
    handleCheckChange(event) {
        if(event.target.name === 'isPrivate') {
            this.EditForm.isPrivate = event.detail.checked;
        }
    }
    handleSave() {
        opportunitySaveRecord({ inputOpportunity: JSON.stringify(this.EditForm) })
        .then(result => {
            console.log('result>>>>>>>>>>>'   result);
            if (result === 'success') {
                refreshApex(this.opportunityRecord);
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Opportunity updated',
                        variant: 'success'
                    })
                );
            }
        })
        .catch(error => {
            //
        });
    }
}

opportunitySaveRecordController.cls

代码语言:javascript复制
public with sharing class opportunitySaveRecordController {
    @AuraEnabled
    public static String opportunitySaveRecord(String inputOpportunity) {
        // Opportunity opportunity =
        //     (Opportunity)JSON.deserializeStrict(inputOpportunity, Opportunity.class);
        OpportunityWrapper opportunityW =
            (OpportunityWrapper)JSON.deserializeStrict(inputOpportunity, opportunitySaveRecordController.OpportunityWrapper.class);
        system.debug('opportunityW>>>>>>>>>>>>>' opportunityW);
        Opportunity currentOpportunity = new Opportunity();
        currentOpportunity.Id = opportunityW.Id;
        currentOpportunity.Name = opportunityW.name;
        currentOpportunity.OwnerId = opportunityW.ownerId;
        currentOpportunity.IsPrivate = opportunityW.isPrivate;
        currentOpportunity.CloseDate = Date.valueOf(opportunityW.closeDate);
        currentOpportunity.AccountId = opportunityW.accountId;
        currentOpportunity.StageName = opportunityW.stageName;
        system.debug('currentOpportunity>>>>>>>>>>>>>' currentOpportunity);
        Database.SaveResult resultObj = Database.update(currentOpportunity, false);
        if (resultObj.isSuccess()){
            system.debug('更新成功>>>>>>>>>>>>>>:::::');
            return 'success';
        } else {
            system.debug('実行結果エラー>>>>>>>>::'   resultObj.getErrors());
            return 'error';
        }
    }
    public class OpportunityWrapper {
        public String id;
        public String name;
        public String ownerId;
        public Boolean isPrivate;
        public String closeDate;
        public String accountId;
        public String stageName;
    }
    @AuraEnabled(cacheable=true)
    public static Opportunity getOpportunityByRecordId(String recordId) {
        Opportunity opportunityItem =
            [SELECT Id,Name,
                    OwnerId,
                    IsPrivate,
                    CloseDate,
                    AccountId,
                    StageName
                    from
                        Opportunity
                    where
                        Id = :recordId limit 1];
        system.debug('opportunityItem>>>>>>>>>>>' opportunityItem);
        return opportunityItem;
    }
}

效果展示:

初期表示:↓↓↓↓↓

更新后:↓↓↓↓↓↓

看下边测试效果,初期数据取得从【getRecord】改成Apex之后,虽然在更新成功时调用方法【refreshApex】,但还是没有刷新其它Component的数据。

打开其它Component↓↓↓↓↓↓

解决方法是调用方法【getRecordNotifyChange】,可以对指定RecordId的数据进行取得,更新并更新Lightning Data Services缓存,修改后的dreamHouseOpportunityEditForm4.js

效果展示:

初期表示↓↓↓↓↓

更新后画面↓↓↓↓↓

其它component:↓↓↓↓↓

数据已经自动刷新。

0 人点赞