0

I got the following error while executed the @AuraEnabled method from community public page(with LWC) with guest user. I think this error may be occurred because the guest user can't be referenced to the record but I need to retrieve the record with guest user from community public page. I already set up the FLS, Object permission at guest user profile.

enter image description here

Here's full source code.

//createRecord.html
<template>
    <lightning-card title="Record with Field Integrity" icon-name="standard:account">
            <div class="slds-var-p-around_x-small">
                <lightning-input label="Name" value={rec.Name} onchange={handleNameChange}></lightning-input>
                <lightning-input label="Industry" value={rec.Industry} onchange={handleIndChange}></lightning-input>
                <lightning-input type="Phone" label="Phone" value={rec.Phone} onchange={handlePhnChange}></lightning-input><br/>
                <lightning-button label="Save" onclick={handleClick}></lightning-button>
            </div>
        </lightning-card>
</template>

//createRecord.js

import { LightningElement, track } from 'lwc';
import ACCOUNT_OBJECT from '@salesforce/schema/Application__c';
import NAME_FIELD from '@salesforce/schema/Application__c.Name__c';
import INDUSTRY_FIELD from '@salesforce/schema/Application__c.Industry__c';
import PHONE_FIELD from '@salesforce/schema/Application__c.Phone__c';
import createAccount from '@salesforce/apex/CreateAcc.createAccount';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { NavigationMixin } from 'lightning/navigation';

export default class CreateRecord extends NavigationMixin(LightningElement) {
  @track url;
  PageRef;

  @track name = NAME_FIELD;
  @track industry = INDUSTRY_FIELD;
  @track phone = PHONE_FIELD;
  rec = {
    Name: this.name,
    Industry: this.industry,
    Phone: this.phone
  };

  connectedCallback() {
    this.PageRef = {
      type: 'comm__namedPage',
      attributes: {
        pageName: 'getsessionstoragevalue'
      }
    };
    this[NavigationMixin.GenerateUrl](this.PageRef).then((url) => {
      this.url = url;
    });
  }

  handleNameChange(event) {
    this.rec.Name = event.target.value;
    console.log('name1', this.rec.Name);
  }

  handleIndChange(event) {
    this.rec.Industry = event.target.value;
    console.log('Industry', this.rec.Industry);
  }

  handlePhnChange(event) {
    this.rec.Phone = event.target.value;
    console.log('Phone', this.rec.Phone);
  }

  handleClick(evt) {
    console.log(`record value is:${JSON.stringify(this.rec)}`);
    createAccount({ param: JSON.stringify(this.rec) })
      .then((result) => {
        this.message = result;
        console.log('encrypted id is:', this.message);
        this.error = undefined;
        sessionStorage.setItem('message', JSON.stringify(result));
        if (this.message !== undefined) {
          this.rec.Name = '';
          this.rec.Industry = '';
          this.rec.Phone = '';
          this.dispatchEvent(
            new ShowToastEvent({
              title: 'Success',
              message: 'Account created',
              variant: 'success'
            })
          );

          evt.preventDefault();
          evt.stopPropagation();
          this[NavigationMixin.Navigate](this.PageRef, true);
        }

        console.log(JSON.stringify(result));
        console.log('result', this.message);
      })
      .catch((error) => {
        this.message = undefined;
        this.error = error;
        this.dispatchEvent(
          new ShowToastEvent({
            title: 'Error creating record',
            message: error.body.message,
            variant: 'error'
          })
        );
        console.log('error', JSON.stringify(this.error));
      });
  }
}

public without sharing class CreateAcc {
  @AuraEnabled
  public static String createAccount(String param) {
    Map<String, Object> paramMap = (Map<String, Object>) JSON.deserializeUntyped(
      param
    );

    Application__c app = new Application__c(
      Name__c = paramMap.get('Name').toString(),
      Phone__c = paramMap.get('Phone').toString(),
      Industry__c = paramMap.get('Industry').toString(),
      is_Visible_to_guest_user__c = true
    );
    insert app;

    //  Blob key = EncodingUtil.base64Decode('');
    //  Blob data = Blob.valueOf(acc.Id);
    //  Blob encrypted = Crypto.encryptWithManagedIV('AES128', key, data);

    //  return EncodingUtil.base64Encode(encrypted);
    return app.id;
  }
}

//getSesssionStorageValue.html

<template>
    <lightning-card title="Record with Field Integrity" icon-name="standard:account">
            <div class="slds-var-p-around_x-small">
                <lightning-input label="Name" value={rec.Name}></lightning-input>
                <lightning-input label="Industry" value={rec.Industry}></lightning-input>
                <lightning-input type="Phone" label="Phone" value={rec.Phone}></lightning-input>
            </div>
        </lightning-card>
</template>
//getSesssionStorageValue.html

import { LightningElement, track } from 'lwc';
import ACCOUNT_OBJECT from '@salesforce/schema/Application__c';
import getAccount from '@salesforce/apex/CreateAcc2.getAccount';
import NAME_FIELD from '@salesforce/schema/Application__c.Name__c';
import INDUSTRY_FIELD from '@salesforce/schema/Application__c.Industry__c';
import PHONE_FIELD from '@salesforce/schema/Application__c.Phone__c';

export default class GetSesssionStorageValue extends LightningElement {
  @track name = NAME_FIELD;
  @track industry = INDUSTRY_FIELD;
  @track phone = PHONE_FIELD;
  rec = {
    Name: this.name,
    Industry: this.industry,
    Phone: this.phone
  };

  connectedCallback() {
    var jsonstr = JSON.parse(sessionStorage.getItem('message'));
    console.log(`getSessionStorageValue.js account id is: ${jsonstr}`);

    console.log(`Before settimeout`);
    var now = new Date();
    setTimeout(function () {
      let now = new Date();
      console.log(`Entered settimeout`);
      console.log(
        now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds()
      );
      getAccount({ accId: jsonstr })
        .then((result) => {
          if (result) {
            var app = JSON.parse(result);
            (this.rec.Name = app.Name__c),
              (this.rec.Industry = app.Industry__c),
              (this.rec.Phone = app.Phone__c);
          }
        })
        .catch((error) => {
          console.log(`error: ${JSON.stringify(error)}`);
        });
    }, 50000);
    console.log(
      now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds()
    );

    // this.rec.Name = jsonstr.Name;
    // this.rec.Industry = jsonstr.Industry;
    // this.rec.Phone = jsonstr.Phone;

    // sessionStorage.removeItem('message');

    console.log(jsonstr);
  }
}

public without sharing class CreateAcc2 {
  @AuraEnabled
  public static String getAccount(String accId) {
    System.debug('get parameter from getsessionstoragevalue:' + accId);

    // Blob key = EncodingUtil.base64Decode('');
    // Blob data = EncodingUtil.base64Decode(accId);
    // Blob decrypted = Crypto.decryptWithManagedIV('AES128', key, data);
    // String accIdStr = '\'' + decrypted.toString() + '\'';
    String accIdStr = '\'' + accId + '\'';

    System.debug('accIdStr is:' + accIdStr);

    List<Application__c> appList = [
      SELECT Name__c, Industry__c, Phone__c
      FROM Application__c
      WHERE Id = :accIdStr
    ];

    if (appList.size() > 0) {
      return System.JSON.serialize(appList[0]);
    }
    return System.JSON.serialize(new Application__c());
  }
}

9
  • Can you confirm if the critical update is activated on your org and the class is added to guest user's profile
    – Raul
    Jul 27 '20 at 11:59
  • Notihng was changed.Already did it. @Raul Jul 27 '20 at 12:28
  • Ah I didn't read this properly, looks like the guest user is not having access to this specific record?
    – Raul
    Jul 27 '20 at 13:02
  • Yep @Raul. The problem is I can't access to the specific record. I got the record while I tried with system administrator. Jul 27 '20 at 13:11
  • Then you will need to look at your sharing model and reevaluate if the guest user should have access to the record. If yes, then you would need to create a guest sharing rule.
    – manjit5190
    Jul 27 '20 at 13:17
0

You are using a bind variable so the line String accIdStr = '\'' + accId + '\''; is not required. This is used in dynamic query using Database.query(). Make sure that you are getting a correct 18 or 15 digit Id like 001XXXXXXXXXXXX and change your query to use accId

List<Application__c> appList = [
      SELECT Name__c, Industry__c, Phone__c
      FROM Application__c
      WHERE Id = :accId
    ];
3
  • Thank you for your answer. I confirmed record Id and query with accId but still can't retrieve the specific record with guest user. Jul 28 '20 at 13:43
  • I retrieved the specific record. Thank you for helping me. @manjit5190 Jul 28 '20 at 14:27
  • Sounds great..!
    – manjit5190
    Jul 28 '20 at 14:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.