前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【salesforce】用lwc 实现community site popup page 覆盖homepage (LWC)

【salesforce】用lwc 实现community site popup page 覆盖homepage (LWC)

原创
作者头像
Merry he
修改2023-05-11 17:21:06
3620
修改2023-05-11 17:21:06
举报
文章被收录于专栏:salesforce学习salesforce学习

需求是针对guest user追加一个验证画面,也就是guest user上来加载的时候会弹出一个画面,让输入邮箱紧接着输入验证码 验证通过才会跳转到home画面,而admin user直接登录home page。

大概流程:

针对以上初版代码实现:

modalPopupLWC.html

代码语言:txt
复制
<template>
    <!-- lightning button for open modal window -->
    <template if:true={pupUpFlag}>
        <!-- Modal/Popup Verify mail -->
            <section class="slds-modal slds-fade-in-open" role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-modal="true" aria-describedby="modal-content-id-1" >
                <div class="slds-modal__container">
                    <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
                        <!--section two-->
                        <template if:true={verifyPageDisplayFlag}>
                                <lightning-layout>
                                    <lightning-layout-item padding="around-small" size="3">
                                        <span>you are trying to access asset site,please insure your account is security.</span></br></br>
                                        <lightning-input type="email" value={emailvalue} onchange={handleEmailChange} label="Please input your email address:"></lightning-input>
                                        </br>
                                        <button class="slds-button slds-button_brand" onclick={submitVerifyMail} title="VerifyMail">Verify</button>
                                    </lightning-layout-item>
                                </lightning-layout>
                        </template>
                        <!--section three-->
                        <template if:true={authCodePageDisplayFlag}>
                            <lightning-layout>
                                <lightning-layout-item padding="around-small" size="3">
                                    <span>please find this code from your lastest email,.</span></br></br>
                                    <lightning-input type="text" value={authcodevalue} onchange={handleAuthcodeChange} label="Please input auth code:"></lightning-input>
                                    </br>
                                    <button class="slds-button slds-button_brand" onclick={submitVerifyAuthcode} title="submitVerifyAuthcode">submit</button>
                                </lightning-layout-item>
                            </lightning-layout>
                        </template>
                    </div>
                </div>
            </section>
            <div class="slds-backdrop slds-backdrop_open"></div>
    </template>
</template>

modalPopupLWC.js

代码语言:txt
复制
import { LightningElement,track,api,wire } from 'lwc';
import getAccessUserInfo from "@salesforce/apex/ModalPopupController.getAccessUserInfo";
import getAccessUserAuthcode from "@salesforce/apex/ModalPopupController.getAccessUserAuthcode";
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class ModalPopupLWC extends LightningElement {
    //Boolean tracked variable to indicate if modal is open or not default value is false as modal is closed when page is loaded 
    @track pupUpFlag = true;
    @track verifyPageDisplayFlag = false;
    @track authCodePageDisplayFlag = false;
    @track emailvalue;
    @api authcodevalue;
    // from apex  controller
    connectedCallback(){
     this.verifyPageDisplayFlag = true;
    } 
   // Email
   handleEmailChange(event){
    this.emailvalue = event.target.value;
    } 
    // AuthCode
    handleAuthcodeChange(event){
        this.authcodevalue = event.target.value;
    } 

    // VerifyMail
    submitVerifyMail(event){
        getAccessUserInfo({emailAdr:this.emailvalue})
        .then(result => {
            if (result.length >0) {
                this.verifyPageDisplayFlag = false;
                this.authCodePageDisplayFlag = true;
            } else {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'mail is not exist',
                        message: 'you could not access the site,please connect adminstrator',
                        variant: 'error'
                    })
                );
            }
        }).catch(error => {
            console.log(JSON.stringify(error));
            if(error.body.pageErrors)
            this.errMsg = error.body.pageErrors[0].message;
            this.showAlert = true;
                this.error = error; 
                this.dispatchEvent(new ShowToastEvent({
                        title: 'Error',
                        message: 'System error,please connect adminstrator',
                        variant: 'error'
                }));
        });
    } 

    // VerifyAuthCode
    submitVerifyAuthcode(event) {
        getAccessUserAuthcode({authCode:this.authcodevalue})
        .then(result => {
            if (result.length > 0) {
                this.pupUpFlag = false;
                this.verifyPageDisplayFlag = false;
                this.authCodePageDisplayFlag = false;
            } else {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'auth code is not correct',
                        message: 'you could not access the site,please connect adminstrator',
                        variant: 'error'
                    })
                );
            }
        }).catch(error => {
            console.log(JSON.stringify(error));
            if(error.body.pageErrors)
            this.errMsg = error.body.pageErrors[0].message;
            this.showAlert = true;
                this.error = error; 
                this.dispatchEvent(new ShowToastEvent({
                        title: 'Error',
                        message: 'System error,please connect adminstrator',
                        variant: 'error'
                }));
        });
    }
}

modalPopupLWC.css

代码语言:txt
复制
.slds-modal__container{
    width: 100% !important;
    max-width: 100% !important;
    padding:inherit;
}
.slds-modal__content{
    height : 100% !important;
    max-height: 100% !important;
}

ModalPopupController.cls

代码语言:txt
复制
    public with sharing class ModalPopupController {

        // get AccessUserInfo by email
        @AuraEnabled(cacheable=false)
        Public static List<AccessUser__c> getAccessUserInfo(String emailAdr){
            System.debug('Start-----');
            List<AccessUser__c> accessUserlist = [SELECT email__c,authCode__c FROM AccessUser__c WHERE email__c = :emailAdr LIMIT 1];
              System.debug('111accessUserlist'+accessUserlist);
              // if email is validate
              if (accessUserlist.size() > 0) {
                  // send email.
                  String authCode = RandomNumber.generateRandomNumber(8);
                  Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                  mail.setSubject('Vefiry Code');
                  mail.setHtmlBody('Vefiry Code is: ' + authCode);
                  string[] toaddress = New String[] {emailAdr};
                  mail.setToAddresses(toaddress);
                  Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                  // update record
                  System.debug('-----startupdate');
                  accessUserlist.get(0).authCode__c = authCode;
                  System.debug('-----authCode' +authCode);
                  update accessUserlist; 
              }
              System.debug('return');
              return accessUserlist;
         }

         // get authcodeInfo
        @AuraEnabled(cacheable=false)
        Public static List<AccessUser__c> getAccessUserAuthcode(String authCode){
            System.debug('Start---authCode--');
            List<AccessUser__c> accessUserlist = [SELECT email__c,authCode__c FROM AccessUser__c WHERE authCode__c = :authCode LIMIT 1];
              System.debug('authCode'+accessUserlist);
              return accessUserlist;
         }
}

针对以上 发现这么做 无论是guest user还是admin user都会先popup一个画面,那么怎么解决呢?

方案1:通过audience去控制,不同的profile去看到不同的画面,比如说homepage,建两套homepage,一个page上有控件,一个page上没有控件,类似下图这种:

发现拽出的控件在headtempleate中,要拽就都有 要不拽就都没有。

要想上来就覆盖住site page,只能把控件拽到headtemplate中。

所以此方案不行

方案2:在js中用user profilename去控制。使用@wire方式,然后在connectcallback中使用this.profileName去判断。

代码语言:txt
复制
    //wire getdata
    import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
    import USER_ID from '@salesforce/user/Id';
    import PROFILE_NAME_FIELD from '@salesforce/schema/User.Profile.Name';
    @track profileName
    @wire(getRecord, {recordId: USER_ID,fields: [PROFILE_NAME_FIELD]})
    user({ error, data }) {
        if (error) {
            // handle error
        } else if (data) {
            this.profileName = getFieldValue(data, PROFILE_NAME_FIELD);
        }
    }
    connectedCallback(){
        if(if (this.profileName!= 'System Administrator') {) {
          // XXXXX
        }
    }

执行的时候发现上来是先加载wire --connectcallback--执行wire

所以connectcallback那个时候使用的this.profilename is undefined.

此处也查了下相关文档:https://developer.salesforce.com/forums/?id=9062I000000IRMSQA4

此方案被pass掉了

方案3:在js中用user profilename去控制。用最标准的从后台取数据方式

ModalPopupController.cls 追加

代码语言:txt
复制
        // getProfileId
        @AuraEnabled(cacheable=false)
        public static Profile getProfile(){
              Profile pro = [SELECT Id,Name FROM Profile WHERE Id = :UserInfo.getProfileId() LIMIT 1];
            return pro;
        }

connectedCallback 修正

代码语言:txt
复制
    connectedCallback(){
        // this.verifyPageDisplayFlag = true;
        getProfile()
        .then(result => {
            if (result != null ) {
            console.log('--->' + JSON.stringify(result));
                if (result.Name != 'System Administrator') {
                    // pupUpFlag is true,verifyPageDisplayFlag is true,authCodePageDisplayFlag is false
                    this.verifyPageDisplayFlag = true;

                } else {
                    // pupUpFlag is false,verifyPageDisplayFlag is false,authCodePageDisplayFlag is false
                    this.pupUpFlag =false;
                }
            } else {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'profile is not exist',
                        message: 'please connect adminstrator',
                        variant: 'error'
                    })
                );
            }
        }).catch(error => {
            console.log(JSON.stringify(error));
            if(error.body.pageErrors)
            this.errMsg = error.body.pageErrors[0].message;
            this.showAlert = true;
                this.error = error; 
                this.dispatchEvent(new ShowToastEvent({
                        title: 'Error',
                        message: 'System error,please connect adminstrator',
                        variant: 'error'
                }));
        });
    } 

方案3可以但是貌似有点麻烦

方案4: 使用userinfo

js中connectcallback中代码如下

代码语言:txt
复制
   connectedCallback(){
        // get current pathname
        this.pathname = basePathName;
        console.log('>>>>>>>'+this.pathname);
        getAccessFlag()
        .then(result => {
            if (result) {
                this.verifyPageDisplayFlag = true;
            } else {
                this.pupUpFlag =false;
            }
        }).catch(error => {
            console.log(JSON.stringify(error));
            if(error.body.pageErrors)
            this.errMsg = error.body.pageErrors[0].message;
            this.showAlert = true;
                this.error = error; 
                this.dispatchEvent(new ShowToastEvent({
                        title: 'Error',
                        message: 'System error,please connect adminstrator',
                        variant: 'error'
                }));
        });
    } 

apex中代码如下:

代码语言:txt
复制
        @AuraEnabled(cacheable=false)
        public static Boolean getAccessFlag() {
          Boolean isAccessFlag = true;
          String userType = UserInfo.getUserType();
          if (userType != 'Guest') {
            isAccessFlag = false;
          }
          return isAccessFlag;
      }

貌似方案4比较省事

方案5:使用'@salesforce/user/isGuest'

代码语言:txt
复制
import isguest from '@salesforce/user/isGuest';
    connectedCallback(){
        this.isGuestUser = isguest;
        if (this.isGuestUser) {
            this.verifyPageDisplayFlag = true;
        } else {
            this.pupUpFlag =false;
        }
    }

啥也不说了还是方案5吧

其它连接:

https://salesforce.fun/2020/11/28/calling-apex-method-with-parameters-from-a-lightning-web-component/

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
验证码
腾讯云新一代行为验证码(Captcha),基于十道安全栅栏, 为网页、App、小程序开发者打造立体、全面的人机验证。最大程度保护注册登录、活动秒杀、点赞发帖、数据保护等各大场景下业务安全的同时,提供更精细化的用户体验。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档