本篇参看:

https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.reactivity_fields

https://developer.salesforce.com/docs/component-library/bundle/lightning-record-edit-form/documentation

碰到之前接触的记录一下,深化一下印象。

一. 解决 lightning-record-edit-form没有入力时,效果和标准不一样的问题

先看一下标准的创建数据的UI,当有必入力字段的表单,点击Save按钮以后,上部会有DIV提示。

我们使用 lightning-record-edit-form实现时,发现onsubmit这种 handler需要再所有的字段都满足情况下才执行,也就是说页面中有 invalid的字段入力情况下,不会提交表单,也自然无法执行 onsubmit对应的方法。这个时候,我们就需要在submit的这个按钮添加 onclick方法去调用后台从而实现尽管提交不了表单还可以正常做一些UI效果的可能。简单代码如下

accountEditWithEditForm.html: 展示两个字段,save button除了在submit基础上,还有 onclick操作。需要注意的是, onclick会先于 onsubmit执行,所以我们可以在 onclick做一些validation操作,成功的话,让onsubmit正常执行表单提交操作。

<template>
<lightning-record-edit-form
record-id={recordId}
object-api-name="Account"
onsubmit={handleSubmit}
>
<lightning-messages></lightning-messages>
<c-error-message-modal is-show-error-div={isShowErrorDiv} error-message-list={errorMessageList}></c-error-message-modal> <lightning-layout multiple-rows="true">
<lightning-layout-item size="6">
<lightning-input-field field-name="Name"></lightning-input-field>
</lightning-layout-item>
<lightning-layout-item size="6">
<lightning-input-field field-name="AnnualRevenue"></lightning-input-field>
</lightning-layout-item> <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-layout>
</lightning-record-edit-form>
</template>

accountEditWithEditForm.js

import { LightningElement,track,api,wire } from 'lwc';
import { updateRecord,getRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { NavigationMixin } from 'lightning/navigation';
import { navigationWhenErrorOccur } from 'c/navigationUtils';
import {isSystemOrCustomError,getPageCustomErrorMessageList,getFieldCustomErrorMessageList} from 'c/errorCheckUtils';
import ACCOUNT_ID_FIELD from '@salesforce/schema/Account.Id';
import ACCOUNT_NAME_FIELD from '@salesforce/schema/Account.Name';
import ACCOUNT_ANNUALREVENUE_FIELD from '@salesforce/schema/Account.AnnualRevenue';
const fields = [
ACCOUNT_ID_FIELD,
ACCOUNT_NAME_FIELD,
ACCOUNT_ANNUALREVENUE_FIELD
];
export default class AccountEditWithEditForm extends NavigationMixin(LightningElement) { @api recordId = '0010I00002U8dBPQAZ';
@track isShowErrorDiv = false;
@track errorMessageList = []; @track isFormValid = true; handleSubmit(event) {
event.preventDefault();
if(!this.isShowErrorDiv) {
const fields = {};
fields[ACCOUNT_ID_FIELD.fieldApiName] = this.recordId;
fields[ACCOUNT_NAME_FIELD.fieldApiName] = event.detail.Name;
fields[ACCOUNT_ANNUALREVENUE_FIELD.fieldApiName] = event.detail.AnnualRevenue;
const recordInput = { fields };
this.errorMessageList = [];
this.isShowErrorDiv = false;
updateRecord(recordInput)
.then(() => {
this.dispatchEvent(
new ShowToastEvent({
title: 'Success',
message: 'Account updated',
variant: 'success'
})
);
}).catch(error => {
let systemOrCustomError = isSystemOrCustomError(error);
if(systemOrCustomError) {
navigationWhenErrorOccur(this,error);
} else {
this.isShowErrorDiv = true;
this.errorMessageList = getPageCustomErrorMessageList(error);
console.log(JSON.stringify(this.errorMessageList));
let errorList = getFieldCustomErrorMessageList(error);
if(errorList && errorList.length > 0) {
errorList.forEach(field => {
this.reportValidityForField(field.key,field.value);
});
}
}
});
}
} handleClick(event) {
let allInputList = Array.from(this.template.querySelectorAll('lightning-input-field'));
let invalidFieldLabel = [];
const allValid = allInputList.forEach(field => {
if(field.required && field.value === '') {
invalidFieldLabel.push(field.fieldName);
this.isShowErrorDiv = true;
}
}); if(this.isShowErrorDiv) {
this.errorMessageList.push('These required fields must be completed: ' + invalidFieldLabel.join(','));
}
} reportValidityForField(fieldName,errorMessage) {
console.log('fieldname : ' + fieldName);
if(fieldName === 'Name') {
this.template.querySelector('.accountName').setCustomValidity(errorMessage);
this.template.querySelector('.accountName').reportValidity();
} else if(fieldName === 'AnnualRevenue') {
this.template.querySelector('.accountRevenue').setCustomValidity(errorMessage);
this.template.querySelector('.accountRevenue').reportValidity();
}
} handleReset(event) {
const inputFields = this.template.querySelectorAll(
'lightning-input-field'
);
if (inputFields) {
inputFields.forEach(field => {
field.reset();
});
}
}
}

展示效果:

二.  「`」 的使用

我们在程序中应该很习惯的使用 track / api这种 reactive的变量,改动以后就可以走 rendercallback 然后前端UI会自动渲染和他关联的。除了使用这两个情况,还可以使用getter方式进行 field reactive操作。官方的描述为,如果字段声明不需要使用 track / api这种reactive变量,尽量不用,所以某些case下,我们可以使用 关键字 ``进行操作。这个标签是键盘的哪个呢,看下图?

看一下官方提供的demo

helloExpressions.html:输入框展示两个入力项,下面展示一个拼以后的大写。

<template>
<lightning-card title="HelloExpressions" icon-name="custom:custom14">
<div class="slds-m-around_medium">
<lightning-input
name="firstName"
label="First Name"
onchange={handleChange}
></lightning-input>
<lightning-input
name="lastName"
label="Last Name"
onchange={handleChange}
></lightning-input>
<p class="slds-m-top_medium">
Uppercased Full Name: {uppercasedFullName}
</p>
</div>
</lightning-card>
</template>

helloExpressions.js:使用 `方式整合两个private的字段,实现reactive的效果。这里需要注意的是,如果使用 `以后必须要使用 ${}将变量套起来,这个是固定的写法。

import { LightningElement } from 'lwc';

export default class HelloExpressions extends LightningElement {
firstName = '';
lastName = ''; handleChange(event) {
const field = event.target.name;
if (field === 'firstName') {
this.firstName = event.target.value;
} else if (field === 'lastName') {
this.lastName = event.target.value;
}
} get uppercasedFullName() {
return `${this.firstName} ${this.lastName}`.trim().toUpperCase();
}
}

效果:

总结:篇中主要总结两点。1是 record-edit-form submit前的onclick使用;2是` 搭配 {}实现 reactive的效果。篇中有错误地方欢迎指出,有不懂的欢迎留言。

Salesforce LWC学习(二十二) 简单知识总结篇二的更多相关文章

  1. Salesforce LWC学习(二十六) 简单知识总结篇三

    首先本篇感谢长源edward老哥的大力帮助. 背景:我们在前端开发的时候,经常会用到输入框,并且对这个输入框设置 required或者其他的验证,当不满足条件时使用自定义的UI或者使用标准的 inpu ...

  2. Salesforce LWC学习(四十) dynamic interaction 浅入浅出

    本篇参考: Configure a Component for Dynamic Interactions in the Lightning App Builder - Salesforce Light ...

  3. Salesforce LWC学习(三十九) lwc下quick action的recordId的问题和解决方案

    本篇参考: https://developer.salesforce.com/docs/component-library/bundle/force:hasRecordId/documentation ...

  4. Salesforce LWC学习(三十) lwc superbadge项目实现

    本篇参考:https://trailhead.salesforce.com/content/learn/superbadges/superbadge_lwc_specialist 我们做lwc的学习时 ...

  5. Salesforce LWC学习(三十二)实现上传 Excel解析其内容

    本篇参考:salesforce lightning零基础学习(十七) 实现上传 Excel解析其内容 上一篇我们写了aura方式上传excel解析其内容.lwc作为salesforce的新宠儿,逐渐的 ...

  6. Salesforce LWC学习(三十四) 如何更改标准组件的相关属性信息

    本篇参考: https://www.cnblogs.com/zero-zyq/p/14548676.html https://www.lightningdesignsystem.com/platfor ...

  7. Salesforce LWC学习(三十六) Quick Action 支持选择 LWC了

    本篇参考: https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.use_quick_act ...

  8. Salesforce LWC学习(三十五) 使用 REST API实现不写Apex的批量创建/更新数据

    本篇参考: https://developer.salesforce.com/docs/atlas.en-us.224.0.api_rest.meta/api_rest/resources_compo ...

  9. Salesforce LWC学习(三十八) lwc下如何更新超过1万的数据

    背景: 今天项目组小伙伴问了一个问题,如果更新数据超过1万条的情况下,有什么好的方式来实现呢?我们都知道一个transaction只能做10000条DML数据操作,那客户的操作的数据就是超过10000 ...

随机推荐

  1. PHP xpath() 函数

    定义和用法 xpath() 函数运行对 XML 文档的 XPath 查询.高佣联盟 www.cgewang.com 如果成功,该函数返回 SimpleXMLElements 对象的一个数组.如果失败, ...

  2. Python程序设计pdf|网盘下载内附提取码

    点击此处下载提取码:5o7z 本书提出了以理解和运用计算生态为目标的Python语言教学思想,不仅系统讲解了Python语言语法,同时介绍了从数据理解到图像处理的14个Python函数库,向初学Pyt ...

  3. 7.11 NOI模拟赛 qiqi20021026的T1 四个指针莫队 trie树

    LINK:qiqi20021026的T1 考场上只拿到了50分的\(nq\)暴力. 考虑一个区间和一个区间配对怎么做 二分图最大带权匹配复杂度太高. 先考虑LCS的问题 常见解决方法是后缀数组/tri ...

  4. luogu P4562 [JXOI2018]游戏 组合数学

    LINK:游戏 当L==1的时候 容易想到 答案和1的位置有关. 枚举1的位置 那么剩下的方案为(R-1)! 那么总答案为 (R+1)*R/2(R-1)! 考虑L==2的时候 对于一个排列什么时候会终 ...

  5. 什么是DO,DTO,VO,POJO

    俗话说,没有规矩不成方圆,今天来说一下 Java 中的各种 O(bject). 为什么会出现这些 O? 我们知道,这些 O 不管叫什么名字,其本质都还是对象(Object),既然本质都一样,为什么非要 ...

  6. nodeJs + js 大文件分片上传

    简单的文件上传 一.准备文件上传的条件: 1.安装nodejs环境 2.安装vue环境 3.验证环境是否安装成功 二.实现上传步骤 1.前端部分使用 vue-cli 脚手架,搭建一个 demo 版本, ...

  7. 网络安全传输系统-sprint2线程池技术优化

    part1:线程池工作原理 为满足多客户端可同时登陆的要求,服务器端必须实现并发工作方式.当服务器主进程持续等待客户端连接时,每连接上一个客户端都需一个单独的进程或线程处理客户端的任务.但考虑到多进程 ...

  8. Pytorch_第七篇_深度学习 (DeepLearning) 基础 [3]---梯度下降

    深度学习 (DeepLearning) 基础 [3]---梯度下降法 Introduce 在上一篇"深度学习 (DeepLearning) 基础 [2]---神经网络常用的损失函数" ...

  9. Axios源码分析

    Axios是一个基于promise的HTTP库,可以用在浏览器和node.js中. 文档地址:https://github.com/axios/axios axios理解和使用 1.请求配置 { // ...

  10. C语言学习笔记之原码反码补码

    原码:就是我们自己看的,以及机器输出给我们看的 补码:机器永远是以补码的形式将数据保存在计算机中 正数: 原码=反码=补码 负数: 反码:原码的符号位不变,其他位取反 ,1变0   0变1 补码:机器 ...