首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Salesforce学习 Lwc(三)自定义开发时进行Validation验证

Salesforce学习 Lwc(三)自定义开发时进行Validation验证

原创
作者头像
repick
修改于 2020-12-30 03:08:18
修改于 2020-12-30 03:08:18
94900
代码可运行
举报
文章被收录于专栏:SalesforceSalesforce
运行总次数:0
代码可运行

关于自定义开发过程中,是否可以实现自定义validation验证。

我们在使用 【lightning-record-edit-form】标签开发过程中,表单提交之后,画面输入的内容不符合要求时,error信息显示在项目上。

例:必须项目未输入

lwc代码如下:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<template>
  <lightning-record-edit-form record-id={recordId} object-api-name="Opportunity"
  onsubmit={handleSubmit}>
      <lightning-messages></lightning-messages>
      <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="OrderNumber__c"></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>
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import { LightningElement,track,api,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_ORDER_NUMBER_FIELD from '@salesforce/schema/Opportunity.OrderNumber__c';
const fields = [
    OPPORTUNITY_ID_FIELD,
    OPPORTUNITY_NAME_FIELD,
    OPPORTUNITY_ORDER_NUMBER_FIELD
];
export default class OpportunityDetailEditWithEditForm extends NavigationMixin(LightningElement) {

    @api recordId = '0066g00000GQ4GyAAL';
    @track isShowErrorDiv = false;
    @track errorMessageList = [];

    @track isFormValid = true;

    handleSubmit(event) {
        event.preventDefault();
        if(!this.isShowErrorDiv) {
            const fields = {};
            fields[OPPORTUNITY_ID_FIELD.fieldApiName] = this.recordId;
            fields[OPPORTUNITY_NAME_FIELD.fieldApiName] = event.detail.Name;
            fields[OPPORTUNITY_ORDER_NUMBER_FIELD.fieldApiName] = event.detail.OrderNumber__c;
            const recordInput = { fields };
            this.errorMessageList = [];
            this.isShowErrorDiv = false;
            updateRecord(recordInput)
            .then(() => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Opportunity updated',
                        variant: 'success'
                    })
                );
            }).catch(error => {
                //
            });
        }
    }
    handleReset(event) {
        const inputFields = this.template.querySelectorAll(
            'lightning-input-field'
        );
        if (inputFields) {
            inputFields.forEach(field => {
                field.reset();
            });
        }
    }
}

这种情况,跟标准UI有一定的区别,下边是标准UI,如图所示,画面头部也有显示error信息。

解决方法:首先开发error显示用lwc画面,然后在表单提交按钮上增加【onclick】事件,因为onclick事件会优先于onsubmit被执行。所以画面上的validation验证可以在onclick事件中执行,验证成功之后,会执行onsubmit

error页面的lwc:

errorMessageModal.html

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<template>
  <template if:true={isShowErrorDiv}>
      <div class="pageLevelErrors" tabindex="-1" >
          <div class="desktop forcePageError" aria-live="assertive" data-aura-class="forcePageError">
              <div class="genericNotification">
                  <span class="genericError uiOutputText" data-aura-class="uiOutputText">
                      このページのエラーを確認してください。
                  </span>
              </div>
              <template if:true={isShowMessage}>
                  <ul class="errorsList">
                      <template for:each={errorMessageList} for:item="errorMessageItem">
                          <li key={errorMessageItem}>{errorMessageItem}</li>
                      </template>
                  </ul>
              </template>

          </div>
      </div>
  </template>
</template>

errorMessageModal.js

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import { LightningElement,api,track } from 'lwc';

export default class ErrorMessageModal extends LightningElement {
  @api isShowErrorDiv = false;
  @api errorMessageList = [];
  @track isShowMessage = false;
  renderedCallback() {
      if(this.errorMessageList && this.errorMessageList.length > 0) {
          this.isShowMessage = true;
      } else {
          this.isShowMessage = false;
      }
  }
}

errorMessageModal.css

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
.forcePageError {
  border-bottom: 1px solid var(--lwc-colorBorderSeparatorAlt,rgb(221, 219, 218));
  margin-bottom: var(--lwc-spacingMedium,1rem);
  padding-bottom: var(--lwc-spacingSmall,0.75rem);
}

.forcePageError.desktop .genericNotification {
  font-weight: var(--lwc-fontWeightLight,300);
  border-radius: var(--lwc-borderRadiusMedium,0.25rem);
}

.forcePageError .genericNotification {
  background: var(--lwc-colorBackgroundToastError,rgb(194, 57, 52));
  padding: var(--lwc-spacingMedium,1rem);
  color: var(--lwc-colorTextModal,rgb(255, 255, 255));
  line-height: var(--lwc-lineHeightHeading,1.25);
}

.forcePageError .errorsList {
  list-style: none;
  color: var(--lwc-colorTextError,rgb(194, 57, 52));
  line-height: var(--lwc-lineHeightText,1.5);
  margin: 0;
  padding: var(--lwc-spacingXSmall,0.5rem) var(--lwc-spacingMedium,1rem) var(--lwc-spacingXxSmall,0.25rem) var(--lwc-spacingMedium,1rem);
}

lwc代码如下:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<template>
  <lightning-record-edit-form record-id={recordId} object-api-name="Opportunity"
  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="OrderNumber__c"></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>
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import { LightningElement,track,api,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_ORDER_NUMBER_FIELD from '@salesforce/schema/Opportunity.OrderNumber__c';
const fields = [
    OPPORTUNITY_ID_FIELD,
    OPPORTUNITY_NAME_FIELD,
    OPPORTUNITY_ORDER_NUMBER_FIELD
];
export default class OpportunityDetailEditWithEditForm extends NavigationMixin(LightningElement) {

    @api recordId = '0066g00000GQ4GyAAL';
    @track isShowErrorDiv = false;
    @track errorMessageList = [];

    @track isFormValid = true;

    handleSubmit(event) {
        event.preventDefault();
        if(!this.isShowErrorDiv) {
            const fields = {};
            fields[OPPORTUNITY_ID_FIELD.fieldApiName] = this.recordId;
            fields[OPPORTUNITY_NAME_FIELD.fieldApiName] = event.detail.Name;
            fields[OPPORTUNITY_ORDER_NUMBER_FIELD.fieldApiName] = event.detail.OrderNumber__c;
            const recordInput = { fields };
            this.errorMessageList = [];
            this.isShowErrorDiv = false;
            updateRecord(recordInput)
            .then(() => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Opportunity updated',
                        variant: 'success'
                    })
                );
            }).catch(error => {
                //
            });
        }
    }

    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(','));
        }
    }
    handleReset(event) {
        const inputFields = this.template.querySelectorAll(
            'lightning-input-field'
        );
        if (inputFields) {
            inputFields.forEach(field => {
                field.reset();
            });
        }
    }
}

修改后效果:

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
Salesforce学习 Lwc(一) lightning-record-edit-form标签
使用lightning-record-edit-form组件创建一个表单,该表单用于添加Salesforce记录或更新对象上现有记录中的字段。
repick
2020/12/08
1.4K0
Salesforce 自定义List Button(二) VfPage如何打开Lwc
上一篇做成的ListButton可以直接打开VfPage,VfPage也可以引用Lwc,从而实现打开Lwc画面的做法。
repick
2022/03/31
8720
Salesforce 自定义List Button(二) VfPage如何打开Lwc
Salesforce学习 Lwc(四)自定义开发 项目的label名重写
Lwc中开发中,通常情况下使用【lightning-input-field】,好处是通过使用【field-name】可以直接绑定项目即可实现画面项目与Object的Field之间的绑定。
repick
2020/12/16
5600
Salesforce学习 Lwc(二) 自定义开发ApexClass应用
使用Lwc时候,有时会遇到因为权限问题无法更新的状况,这个时候就要通过ApexClass进行更新操作,因为ApexClass可以无视权限,下边这个例子就是ApexClass与LightningWebComponent结合,实现更新画面上的项目。
repick
2020/12/12
1.1K0
Salesforce How To Refresh Page Data in Lightning Web Component(三)
使用Lwc打开一个新的浏览器窗口,当关闭窗口时也可以进行刷新操作,如下,点击加号按钮,打开登录画面,当登录成功时刷新ListView列表。
repick
2022/05/03
4950
Salesforce How To Refresh Page Data in Lightning Web Component(三)
Salesforce LWC学习(二十二) 简单知识总结篇二
https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.reactivity_fields
Zero-Zhang
2020/09/01
5890
Salesforce LWC学习(二十二) 简单知识总结篇二
Salesforce LWC学习(三十) lwc superbadge项目实现
本篇参考:https://trailhead.salesforce.com/content/learn/superbadges/superbadge_lwc_specialist
Zero-Zhang
2020/12/29
1.7K0
salesforce零基础学习(一百一十二)项目中的零碎知识点小总结(四)
本篇参考: https://trailblazer.salesforce.com/issues_view?id=a1p4V0000003znDQAQ https://salesforce.stacke
Zero-Zhang
2022/03/22
7190
salesforce零基础学习(一百一十二)项目中的零碎知识点小总结(四)
Salesforce LWC学习(十) 前端处理之 list 处理
本篇参看:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array
Zero-Zhang
2020/02/12
9400
Salesforce LWC学习(七) Navigation & Toast
上一篇我们介绍了针对LWC中常用的LDS的适配的wire service以及@salesforce模块提供的相关的service,其实LWC中还提供其他的好用的service,比如针对导航相关的lightning/navigation以及展示toast提示信息相关的lightning/platformShowToastEvent。此篇主要针对这两个service进行简单的介绍。
Zero-Zhang
2019/09/29
1.4K0
Salesforce LWC学习(七) Navigation & Toast
Salesforce LWC学习(十三) 简单知识总结篇一
本篇参考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript
Zero-Zhang
2020/03/24
1.2K0
Salesforce LWC学习(十三) 简单知识总结篇一
Salesforce学习 Lwc(九)【数据初期取得与更新】运用详解
开发自定义画面经常遇到的场景就是增删改查,关于数据更新用到的几个方法进行一下总结,常用到的有以下几种。
repick
2020/12/29
1.1K0
Salesforce LWC学习(二十一) Error浅谈
本篇参考:https://developer.salesforce.com/docs/component-library/documentation/en/lwc/data_error
Zero-Zhang
2020/08/25
1.2K0
Salesforce LWC学习(二十一) Error浅谈
Salesforce Lightning Data Table With Row Actions(二)
下边做成删除子画面,编辑子画面,分别进行消除和编辑操作,如下,点击Edit时,打开编辑子画面进行数据更新,点击Delete时,打开消除子画面进行数据消除。
repick
2022/05/10
7500
Salesforce Lightning Data Table With Row Actions(二)
Salesforce LWC学习(三十三) lightning-datatable 翻页bug处理
本来lightning-datatable这种标签,基本上任何的项目都会用到而且很精通,所以当时感觉没有太大的单独一篇写的必要,在Salesforce LWC学习(三十) lwc superbadge项目实现 中也有使用这个标签的demo,所以有类似需要的小伙伴参考一下也可以照猫画虎搞定需求。项目中遇见了两个datatable的问题,解决以后感觉有必要写一下,后期遇见这种坑的小伙伴可以快速对应。话不多说,先弄一个简单的分页效果的UI,UI很丑,旨在实现功能。
Zero-Zhang
2021/03/27
1K0
Salesforce LWC学习(八) Look Up组件实现
本篇参考https://www.salesforcelwc.in/2019/10/lookup-in-lwc.html,感谢前人种树。
Zero-Zhang
2019/12/25
1.1K0
Salesforce LWC学习(八) Look Up组件实现
Salesforce LWC学习(二十三) Lightning Message Service 浅谈
https://trailhead.salesforce.com/content/learn/superbadges/superbadge_lwc_specialist
Zero-Zhang
2020/09/08
8380
Salesforce LWC学习(二十三) Lightning Message Service 浅谈
Salesforce LWC学习(二十七) File Upload
https://developer.salesforce.com/docs/component-library/bundle/lightning-file-upload/documentation
Zero-Zhang
2020/10/10
7460
Salesforce LWC学习(二十七) File Upload
Salesforce学习 Lwc(十二)【Lightning Message Service】
前边讲过方法【this.dispatchEvent()】的用法,可以实现父子Lwc组件之间的相互调用,今天讲解Communicate Across the DOM with Lightning Message Service,使用【Lightning message service】在Lightning页面内跨DOM进行通信,可以实现在嵌入在同一Lightning页面中的Visualforce页面,Aura组件和Lightning Web组件之间进行通信,可以不用
repick
2021/01/05
1.3K0
Salesforce学习 Lwc(十二)【Lightning Message Service】
Salesforce FileUpload(四) 导入静态资源并显示自定义头像框
我们在项目中,会遇到顾客详细画面,或者用户详细画面需要显示头像功能,下面使用lwc开发一个如下图的自定义组件。
repick
2022/02/10
6030
Salesforce FileUpload(四) 导入静态资源并显示自定义头像框
推荐阅读
相关推荐
Salesforce学习 Lwc(一) lightning-record-edit-form标签
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档