前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Salesforce学习 Lwc(三)自定义开发时进行Validation验证

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

原创
作者头像
repick
修改2020-12-30 11:08:18
8350
修改2020-12-30 11:08:18
举报
文章被收录于专栏:SalesforceSalesforce

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

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

例:必须项目未输入

lwc代码如下:

代码语言:javascript
复制
<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
复制
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
复制
<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
复制
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
复制
.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
复制
<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
复制
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 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 关于自定义开发过程中,是否可以实现自定义validation验证。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com