• Vinay M
  • NEWBIE
  • 75 Points
  • Member since 2016

  • Chatter
    Feed
  • 2
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 22
    Replies
Thought this was going to be simple problem to solve but wasted a day on it so far & no closer.

I have one LWC component, call it lwcParent, which needs to get an item of data e.g. the current user Id from an apex call.  It then passes this to a second LWC component, call it lwcChild, for that component to act upon.  I can pass the data but I need lwcChild to be aware of the passed data in its ConnectedCallback or at least recognise that the new data has been supplied so it can do something to it.

I have a pair of dummy LWC components to demonstrate:-

lwcChild
<template>
    <lightning-input label="User Id" type="text" value={userId}></lightning-input>
</template>
 
import { LightningElement, api } from 'lwc';

export default class LwcChild extends LightningElement {
    @api userId;
    connectedCallback(){
        console.log('starting lwcChild.connectedCallback');
        console.log('lwcChild userId: ' + this.userId);
        console.log('completed lwcChild.connectedCallback');
    }
}
 
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>55.0</apiVersion>
    <isExposed>true</isExposed>
</LightningComponentBundle>

lwcParent
html
<template>
    <article class="slds-card">
        <div data-id="mainDiv" class="slds-card-wrapper">  
            <h1>Parent</h1>
            <c-lwc-child user-id={userId}></c-lwc-child>
        </div>
    </article>
</template>
import { LightningElement, track } from 'lwc';
import getLoggedInUserId from '@salesforce/apex/LightningCommonUtilities.getLoggedInUserId';

export default class LwcParent extends LightningElement {

    @track userId;

    connectedCallback() {
        console.log('starting lwcParent.connectedCallback');
        getLoggedInUserId()
        .then(result => {
            this.userId = result;
            console.log('lwcParent userId: ' + this.userId);
        })
        .catch(error => {
            window.console.log('error (connectedCallback.getLoggedInUserId) =====> '+JSON.stringify(error));
            if(error) {
                window.console.log('@@@@ ERROR '+ error);
            }
        })
        console.log('completed lwcParent.connectedCallback');
    }

}
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" >
    <apiVersion>55.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__RecordPage">
            <objects>
                <object>Contact</object>
            </objects> 
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>
Apex code :-
public with sharing class LightningCommonUtilities{    
    @AuraEnabled(cacheable=true)
    public static string getLoggedInUserId(){
        system.debug('AAb:' + UserInfo.getUserId());
        return UserInfo.getUserId();
    }
}
If I look at the console after it runs I can see :-
lwcParent.js:1 starting lwcParent.connectedCallback
lwcParent.js:1 completed lwcParent.connectedCallback
lwcChild.js:1 starting lwcChild.connectedCallback
lwcChild.js:1 lwcChild userId: undefined
lwcChild.js:1 completed lwcChild.connectedCallback
lwcParent.js:1 lwcParent userId: 00558000001MvGNAA0
So lwcParent isn't getting the userId until after the lwcChild's connectedCallback has completed.  I've also tried this using a wire rather than calling the apex method from connectedCallback but the end result is the same.

Is there a way to either delay the instantiation of lwcChild until lwcParent has loaded the data or for lwcChild to be made aware that the data has changed so that it can call one of its functions?

As always any help appreciated.




 
Hi,
I have a requirement where the user clicks on a button and is navigated to an application.
I have created a function in my JS controller by creating an URL using the following text+ Application ID, but it's not working. Please let me know if you have any suggestions. How do I build my application URL when I know my application ID?

launchApp(){
this[NavigationMixin.Navigate]({
type: 'standard__navItemPage',
attributes:{
url : '/lightning/app/c__' + this.applicationMetadataToshow.Application_ID__c
}
});
}
Hi,
I have a custom LWC residing in record detail page. This LWC is displaying the files associated with the record. When user clicks on the file, I'm using NavigationMixin with 'standard__namedPage' and 'filePreview' to preview the file to the user. If the user deletes this file from the preview, then my LWC is not updating to remove the deleted file.

The LWC updates only when the user manually refreshes the page. But I see other standard related lists automatically refreshing when I delete the file from the preview because I see the spinner on each of those related lists.

When deleting a related file, how is it automatically refreshing the standard related lists on the record detail page? Which event/message do I need to subscribe to in my custom LWC to refresh itself too?

I searched everywhere, and everyone only talk about refresh the standard related lists automatically when custom component does something. But no one talks about the other way round - how to detect a change, or in my case a deletion of record in related list, in a custom LWC residing on the same record detail page?
When attempting to populate the value of a User lookup field via the 'value' attribute, I receive the following error:
lookup.js:1 Uncaught (in promise) Error: LWC component's @wire target property or method threw an error during value provisioning. Original error:
[Unexpected Error when retrieving 'User' Layout Information ]
The dumbed down code looks something like this: 

html
<lightning-input-field field-name="Submitter__c" value={submitter}></lightning-input-field>

JS
import { LightningElement, api, wire, track } from 'lwc';
import Id from '@salesforce/user/Id';

export default class EditableForm extends LightningElement {
@track submitter = Id;

}

The stickler is that this code previously worked. I only found this issue when returning to this form to test an unrelated workaround (changing a manual sharing rule from a flow to a trigger).

Any idea why this is happening? 
Thought this was going to be simple problem to solve but wasted a day on it so far & no closer.

I have one LWC component, call it lwcParent, which needs to get an item of data e.g. the current user Id from an apex call.  It then passes this to a second LWC component, call it lwcChild, for that component to act upon.  I can pass the data but I need lwcChild to be aware of the passed data in its ConnectedCallback or at least recognise that the new data has been supplied so it can do something to it.

I have a pair of dummy LWC components to demonstrate:-

lwcChild
<template>
    <lightning-input label="User Id" type="text" value={userId}></lightning-input>
</template>
 
import { LightningElement, api } from 'lwc';

export default class LwcChild extends LightningElement {
    @api userId;
    connectedCallback(){
        console.log('starting lwcChild.connectedCallback');
        console.log('lwcChild userId: ' + this.userId);
        console.log('completed lwcChild.connectedCallback');
    }
}
 
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>55.0</apiVersion>
    <isExposed>true</isExposed>
</LightningComponentBundle>

lwcParent
html
<template>
    <article class="slds-card">
        <div data-id="mainDiv" class="slds-card-wrapper">  
            <h1>Parent</h1>
            <c-lwc-child user-id={userId}></c-lwc-child>
        </div>
    </article>
</template>
import { LightningElement, track } from 'lwc';
import getLoggedInUserId from '@salesforce/apex/LightningCommonUtilities.getLoggedInUserId';

export default class LwcParent extends LightningElement {

    @track userId;

    connectedCallback() {
        console.log('starting lwcParent.connectedCallback');
        getLoggedInUserId()
        .then(result => {
            this.userId = result;
            console.log('lwcParent userId: ' + this.userId);
        })
        .catch(error => {
            window.console.log('error (connectedCallback.getLoggedInUserId) =====> '+JSON.stringify(error));
            if(error) {
                window.console.log('@@@@ ERROR '+ error);
            }
        })
        console.log('completed lwcParent.connectedCallback');
    }

}
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" >
    <apiVersion>55.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__RecordPage">
            <objects>
                <object>Contact</object>
            </objects> 
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>
Apex code :-
public with sharing class LightningCommonUtilities{    
    @AuraEnabled(cacheable=true)
    public static string getLoggedInUserId(){
        system.debug('AAb:' + UserInfo.getUserId());
        return UserInfo.getUserId();
    }
}
If I look at the console after it runs I can see :-
lwcParent.js:1 starting lwcParent.connectedCallback
lwcParent.js:1 completed lwcParent.connectedCallback
lwcChild.js:1 starting lwcChild.connectedCallback
lwcChild.js:1 lwcChild userId: undefined
lwcChild.js:1 completed lwcChild.connectedCallback
lwcParent.js:1 lwcParent userId: 00558000001MvGNAA0
So lwcParent isn't getting the userId until after the lwcChild's connectedCallback has completed.  I've also tried this using a wire rather than calling the apex method from connectedCallback but the end result is the same.

Is there a way to either delay the instantiation of lwcChild until lwcParent has loaded the data or for lwcChild to be made aware that the data has changed so that it can call one of its functions?

As always any help appreciated.




 
I'm using the built-in input validation feature. When an invalid input is entered and the user clicks outside the input box, sometimes that input disappears; the associated error message does not get displayed. I'd prefer the invalid input to remain in the input box. What might cause the input to sometimes disappear?
I'm trying to convert a javascript button to Lightning experience using the SFDC converter but I keep getting a vague error: User-added image

So I tried coping the data in the Preview window in the converter and creating a Lightning component using the developer console but I couldn't get it to work. I've never created a Lightning component before so I'm unsure what the exact steps are. Could someone assist me?
Here's what the preview of the javascript looks like:
User-added image
So I copied that and went to dev console, selected 
File>New Lightning Component and named it and selected the Lightning Quick action checkbox (not sure if that's what I was supposed to do) then clicked submit button. Not sure what to do from there so I went to File and clicked Save. I got this error now:User-added imageI'm unsure what to do to get this javascript button working/replicated for Lightning now. any help would be appreciated. I am NOT a developer so my skills are limited.

 
I have created a lightning Web component that accepts input from user and saves the data to the custom setting. Now i want to check duplication of the record based on two fields. Let suppose Name and Contact, i.e if Name and Contact together of the current record is is same as any other existing record then it should not be saved.
How do i handle that in apex And JavaScript?

Thanks In Advance

Hi guys so im facing issue with getRecords adapter when i hard code to adapter configuration Ids of records it works but when i send a array of string as it is requierd data is not fetching 

 

import { LightningElement, api, wire, track } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { getRecords } from 'lightning/uiRecordApi';
import getResult from '@salesforce/apex/CustomUser.getResult';
const FIELDS = [
    'Result__c.Name',
    'Result__c.User__c',
    'Result__c.License_Proposal__c',
    'Result__c.Current_License__c'
];
const COLS = [
    { label: 'Id', fieldName: 'Id' },
    { label: 'Email', fieldName: 'Email' },
    { label: 'Current License', fieldName: 'Current License' },
    { label: 'License Proposal', fieldName: 'License Proposal' }
];
export default class TestCmp extends LightningElement {
    @api recordId;
    contacts;
    @track records = [];
    columns = COLS;
    testing = [];
    @wire(getResult)
    resultHandler({ data, error }) {
        if (data) {
            console.log(data);
            this.records = data;
            console.log(Array.isArray(this.records));
        } else if (error) {
            console.error(error);
        }
    }
    @wire(getRecords, {
        records: [
            {
                recordIds: '$records',
                fields: FIELDS
            }
        ]
    })
    wiredRecord({ error, data }) {
        if (error) {
            let message = 'Unknown error';
            if (Array.isArray(error.body)) {
                message = error.body.map((e) => e.message).join(', ');
            } else if (typeof error.body.message === 'string') {
                message = error.body.message;
            }
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error loading Result',
                    message,
                    variant: 'error'
                })
            );
        } else if (data) {
            console.log(data);
            this.contacts = data.results.map((item) => {
                return {
                    Id: this.getValue(item, 'User__c'),
                    Email: this.getValue(item, 'Name'),
                    'Current License': this.getValue(
                        item,
                        'Current_License__c'
                    ),
                    'License Proposal': this.getValue(
                        item,
                        'License_Proposal__c'
                    )
                };
            });
            console.log('i m here ' + this.contacts);
            // this.name = this.contacts.results[1].result.fields.Name.value;
            // this.phone = this.contacts.results[1].result.fields.Phone.value;
        }
    }
    getValue(data, field) {
        return data.result.fields[field].value;
    }

But if i give it ['a0*********QAU', 'a06**********AU']  instead of array of '$records' it works  

  • September 25, 2022
  • Like
  • 0
Hi,
I have a requirement where the user clicks on a button and is navigated to an application.
I have created a function in my JS controller by creating an URL using the following text+ Application ID, but it's not working. Please let me know if you have any suggestions. How do I build my application URL when I know my application ID?

launchApp(){
this[NavigationMixin.Navigate]({
type: 'standard__navItemPage',
attributes:{
url : '/lightning/app/c__' + this.applicationMetadataToshow.Application_ID__c
}
});
}
I have a custom lwc component to upload multiple files in a given record. I want that the files uploaded under the Notes and Attachment section of that record to be displayed in a datatable on the same custom component and the user should have access to remove the attachment from the component rather than going to the record and deleting it.
Below is my code:

Markup:
<template>
    <div class="ds_custom_body">
        <div class="ds_width-container js-enabled">
            <div class={formGroupClass}>
                <label class="ds_label" for="file-upload">
                    
                <img id="u21_img" class="img " src="https://d1icd6shlvmxi6.cloudfront.net/gsc/7CR7K2/66/9d/a7/669da75ef5c94006bba8c6b217a48a59/images/return_on_investment__3__1/file_upload_u21.svg?pageId=63f05657-437f-4a8d-8fa3-42798c6e5946">
                &nbsp;&nbsp;&nbsp;&nbsp;
                    {fileUploadLabel}
                </label>
                <span id="file-upload-error" class="ds_error-message slds-hyphenate" if:true={hasErrors}>
                    <span class="ds_visually-hidden">Error:</span>&nbsp;{errorMessage}
                </span>
                <input class={inputClass} id="file-upload" name="file-upload" type="file" accept={acceptedFormats}
                    multiple onchange={handleFilesChange} aria-describedby="file-upload-error" hidden />

                <div if:true={fileNames}>
                    {fileNames}
                </div><br />
                <template if:true={data}>
                    <lightning-card title="Uploaded Files" icon-name="standard:account">
                        <div style="width: auto;">
                            <lightning-datatable data={data} 
                                                 columns={columns} 
                                                 key-field="id">
                            </lightning-datatable>
                        </div>
                    </lightning-card>
                </template>
            </div>
        </div>
    </div>
</template>

Js Controller:
import { LightningElement, wire, api, track } from 'lwc';
 import { FlowAttributeChangeEvent } from 'lightning/flowSupport';
 import saveFiles from '@salesforce/apex/FileUploadController.saveFiles';
 import { MessageContext, publish, subscribe, unsubscribe } from 'lightning/messageService';
 import REGISTER_MC from '@salesforce/messageChannel/registrationMessage__c';
 import VALIDATION_MC from '@salesforce/messageChannel/validateMessage__c';
 import VALIDATION_STATE_MC from '@salesforce/messageChannel/validationStateMessage__c';

 const columns = [{
    label: 'Title',
    fieldName: 'FileName',
    type: 'url',
    typeAttributes: {
        label: {
            fieldName: 'Title'
        },
        target: '_blank'
    }
}];
 
 export default class GovFileUpload extends LightningElement {
     
     @api fieldId = "uploadField";
     @api fileUploadLabel = "Upload a file";
     @api acceptedFormats = "image/png, image/jpg, .pdf, .doc, .docx, .zip";
     @api maxFileSizeInMB = 2;
     @api required = false;
     @api errorMessage = "Select a file"; 
 
     @api filesUploadedCollection = []; 
     @api filesUploadedExpanded = []; 
     @api filesUploaded; 
 
     @api useApexToSaveFile;   
     @api recordId = "";
     
     @track hasErrors = false;
     @track fileNames = '';
     @track columns = columns;
 
     get formGroupClass() {
         let formGroupClass = "";
         formGroupClass =  this.hasErrors ? "ds_form-group ds_form-group--error" : "ds_form-group";
         return formGroupClass;
     }
 
     get inputClass() {
         let inputClass = "";
         inputClass =  this.hasErrors ? "ds_file-upload ds_file-upload--error" : "ds_file-upload";
         return inputClass;
     }
 
     handleFilesChange(event) {
         this.clearError();
         let files = event.target.files;
         if(files.length > 0) {
             let filesName = '';
             for (let i = 0; i < files.length; i++) {
                 let file = files[i];
                 filesName = filesName + file.name + ',';
                 if(file.size > (this.maxFileSizeInMB * 1000000)) {
                     this.hasErrors = true;
                     this.errorMessage = `The selected file(s) must be smaller than ${this.maxFileSizeInMB} MB`;
                     return;
                 }
                 let freader = new FileReader();
                 freader.onload = f => {
                     let base64 = 'base64,';
                     let content = freader.result.indexOf(base64) + base64.length;
                     let fileContents = freader.result.substring(content);
                     if (i==0) {
                         this.filesUploaded = file.name;
                     } else {
                         this.filesUploaded = this.filesUploaded + ';' + file.name;
                     }
                     this.filesUploadedCollection.push(file.name);
                     this.filesUploadedExpanded.push({
                         Title: file.name,
                         VersionData: fileContents
                     });
                     this.useApexToSaveFile = true;
                     if(this.recordId !== "" && this.useApexToSaveFile && (i+1) === files.length) {
                         this.handleSaveFiles();
                     } 
                     if((i+1) === files.length) {
                         this.dispatchUploadEvent();
                     }  
                 };
                 freader.readAsDataURL(file);
             }
             this.fileNames = filesName.slice(0, -1);
         }
     }
 
     handleSaveFiles() {
         saveFiles({
             filesToInsert: this.filesUploadedExpanded,
             strRecId: this.recordId
          })
         .then(data => {
         })
         .catch(error => {
             this.hasErrors = true;
             this.errorMessage = error;
         }); 
     }
 
     // messaging attributes
     @wire(MessageContext) messageContext;
     validateSubscription;
 
     // LMS functions
     subscribeMCs() {
         if (this.validateSubscription) {
             return;
         }
         this.validateSubscription = subscribe (
             this.messageContext,
             VALIDATION_MC, (message) => {
                 this.handleValidateMessage(message);
             });
     }
 
     unsubscribeMCs() {
         unsubscribe(this.validateSubscription);
         this.validateSubscription = null;
     }
 
     connectedCallback() {
         // subscribe to the message channels
         this.subscribeMCs();
 
         // publish the registration message after 0.1 sec to give other components time to initialise
         setTimeout(() => {
             publish(this.messageContext, REGISTER_MC, { componentId: this.fieldId });
         }, 100);
     }
 
     disconnectedCallback() {
         this.unsubscribeMCs();
     }
 
     handleValidateMessage(message) {
         this.handleValidate();
     }
 
     @api 
     handleValidate() {
         this.hasErrors = false;
         if(this.required && this.filesUploadedExpanded.length === 0) {
             this.hasErrors = true;
         }
         publish(this.messageContext, VALIDATION_STATE_MC, {
             componentId: this.fieldId,
             isValid: !this.hasErrors,
             error: this.errorMessage
         });
         return !this.hasErrors;
     }
 
     @api 
     clearError() {
         this.hasErrors = false;
     }
 
     dispatchUploadEvent() {
         // tell the flow engine about the upload
         const attributeChangeEvent = new FlowAttributeChangeEvent('value', JSON.stringify(this.filesUploaded));
         this.dispatchEvent(attributeChangeEvent);
 
         // tell any parent components about the upload
         const fileUploadEvent = new CustomEvent('fileUpload', {
             detail: {
                 id: this.fieldId,
                 value: JSON.stringify(this.filesUploaded)
             }
         });
         this.dispatchEvent(fileUploadEvent);
     }

     removeReceiptImage(event) {
        var index = event.currentTarget.dataset.id;
        this.filesData.splice(index, 1);
    }
 
 }

MetaXml:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>55.0</apiVersion>
    <isExposed>true</isExposed>
    <description>This help users select and upload a file.</description>
    <masterLabel>Gov File Upload</masterLabel>
    <targets>
        <target>lightning__FlowScreen</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__FlowScreen">
            <property name="fieldId" type="String" label="Field Id" required="true" default="uploadField" description="Field Id - must be unique to this process"/>
            <property name="fileUploadLabel" type="String" label="Field Label" default="Upload a file" description="The label to display"/>
            <property name="acceptedFormats" type="String" label="Accepted File Formats" default="image/png, image/jpg, .pdf, .doc, .docx, .zip" description="A valid case-insensitive filename extension, starting with a period (.) character. For example: .jpg, .pdf, or .doc."/>
            <property name="maxFileSizeInMB" type="Integer" label="Max Files Size Allowed (in MB)" default="2" description="The maximum file size allowed to upload in MB (Max Value should not be greater than Salesforce Standards)"/>
            <property name="required" type="Boolean" label="Required?" default="false" description="If True, user must enter at least one file."/>
            <property name="errorMessage" type="String" label="Error Message" default="Select a file" description="Error Message to display"/>
            <property name="useApexToSaveFile" type="Boolean" label="Use Apex Function to Save File"  default="true" description="Must be set to True - {!$GlobalConstant.True}. [This feature is not yet enabled]"/>
            <property name="recordId" type="String" label="Related Record ID" description="The ID of the Salesforce record to associate the files with.  A value must be entered or the flow will fail."/>        
            <property name="filesUploaded" type="String" label="Uploaded file names" description="Semi-colon delimited list of file names uploaded. Text variable. Output only."/>
            <property name="filesUploadedCollection" type="String[]" label="Uploaded file names Collection" description="A collection variable to hold the names of any files uploaded. Output only."/>
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

Apex Controller:
public with sharing class FileUploadController {
    
    @AuraEnabled
    public static void saveFiles(List<Object> filesToInsert, String strRecId) { 
        List<Id> lstCntVerIds = new List<Id>();
        List<ContentVersion> lstVersionsToInsert = new List<ContentVersion>();
        for (Object objFile : filesToInsert) {
            FileInfo fileData = (FileInfo)JSON.deserialize(JSON.serialize(objFile), FileInfo.class);
            ContentVersion objCntVersion = new ContentVersion();
            objCntVersion.PathOnClient = fileData.Title;
            objCntVersion.Title = fileData.Title;
            objCntVersion.VersionData = fileData.VersionData;
            lstVersionsToInsert.add(objCntVersion);
        }
        
        if(!lstVersionsToInsert.isEmpty()) {
            List<Database.SaveResult> res = Database.INSERT(lstVersionsToInsert);
            for (Database.SaveResult saveResult : res) {
                if(saveResult.isSuccess()) {
                    lstCntVerIds.add(saveResult.getId());
                }
            }
            List<ContentDocumentLink> lstCntDocLinkToInsert = getLstCntDocLink(lstCntVerIds, strRecId);
            if(!lstCntDocLinkToInsert.isEmpty()) {
                try {
                    List<Database.SaveResult> res2 = Database.INSERT(lstCntDocLinkToInsert);
                } catch (DmlException dmlEx) {
                    throw new AuraHandledException('Could not insert document to database. Check user permissions ' + dmlEx.getMessage());
                }
            }
        }  
    }
    
    private static List<ContentDocumentLink> getLstCntDocLink(List<Id> lstCntVerIds, String strRecordId) {
        List<ContentDocumentLink> lstCntDocLink = new List<ContentDocumentLink>();
        List<ContentVersion> lstContVersion = new List<ContentVersion>();
        if(!lstCntVerIds.isEmpty()) {
            if(ContentVersion.SObjectType.getDescribe().isAccessible()) {
                lstContVersion = [SELECT ContentDocumentId FROM ContentVersion WHERE Id IN :lstCntVerIds];
            }
            for(ContentVersion objCntVer : lstContVersion) {
                ContentDocumentLink objCntDocLink = new ContentDocumentLink();
                objCntDocLink.ContentDocumentId = objCntVer.ContentDocumentId;
                objCntDocLink.LinkedEntityId = strRecordId;
                objCntDocLink.ShareType = 'V';
                lstCntDocLink.add(objCntDocLink);
            }
        }
        return lstCntDocLink;
    }
    
    public class FileInfo {
        public String Title;
        public Blob VersionData;
    }
    
}

​​​​​​​​​​​​​​
I've been unable to force a refresh of a child component in lwc.
Basically, I have something like:
<template>
   <c-child-lwc-component userid={selectedUserId}></c-child-lwc-component>

  <lightning-button  label="Do Something" 
	onclick={handleDoSomething}></lightning-button>
</template>
When the button is hit, I'm calling Apex to do something with the user id and when it's done, the childLwcComponent, if it re-renders properly, will show different results. But after calling the apex function, I cannot get the child component to re-render fully.
 
@track selectedUserId;
import invokeMyApexMethod from '@salesforce/apex'MyClass.myApexMethod';

handleDoSomething() {
		invokeMyApexMethod({
			userId: this.selectedUserId
		})
		.then(result => {
			this.trackedfield = result;
			this.trackederror = undefined;
// Need to re-load child component here!
		}).catch(error => {
			console.log(error);
			this.trackederror = error;
			this.trackedvalue = undefined;
		});
}
I have tried using refreshApex referencing this.selectedUserId. I've  also tried adding a dummy, tracked parameter to my child lwc component so that I can change that value every time my apex method has completed. but it still will not re-load the child component.
 
Hi 
How to change standard button background color(New Record).
I am trying to built a age calculator. calculator take input from calendar and output age. but this program don't show anything.

Agecalculator.html
<template>
    <lightning-card  title="Age Calculator">
        <lightning-button variant="brand" label="Calculate"  slot="actions" onclick={calculateDOB}></lightning-button>
        <p class="slds-p-horizontal_small">
            <lightning-input type="date" name="BirthDate" label="Enter Your Date Of Birth" placeholder="type here..." value={birthdate} onchange= {handleChangeNum1}></lightning-input>
            result---{result}
        </p>
    </lightning-card>
</template>
AgeCalculator.js
export default class AgeCalculator extends LightningElement {
    @track result;
    @track birthdate;
    today = new Date();


    handleChangeNum1(event){
        const inpurdate = event.target.name;
        const inputvalue= event.target.value;
        if(inpurdate=='BirthDate'){
            this.birthdate=inputvalue;
        }

    }
    calculateDOB (event) {

        this.result=today.getfullyear-this.birthdate.getfullyear;
    }
}


 
I am trying to create custom Lighting Web Components to display a doughnut chart that process Salesforce data from the server.  I choose LWCC to build my custom chart.  Here is documentation: https://salesforcelabs.github.io/LightningWebChartJS/

When I use static values to build a graph, it works.  But when I try to use SOQL property in js file, I don't seem to grab the data properly.  I could not find any examples of using this property inside Lighting Web component:
Here is my JavaScript file code:

import { LightningElement, track} from 'lwc';
import chartjs from '@salesforce/resourceUrl/ChartJs';
import { loadScript } from 'lightning/platformResourceLoader';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class MyCustomChart extends LightningElement {
    @track isChartJsInitialized;
    chart;
    config = {
        type: 'doughnut',
        SOQL:'SELECT MailingState label, Count(Id) value FROM Contact WITH SECURITY_ENFORCED GROUP BY MailingState LIMIT 100',
options: {
            title: {
                display: true,
                text: 'Number of Members'
            }
        }
    };
    renderedCallback() {
        if (this.isChartJsInitialized) {
            return;
        }
        this.isChartJsInitialized = true;
        Promise.all([
            loadScript(this, chartjs)
        ]).then(() => {
            const ctx = this.template.querySelector('canvas.linechart').getContext('2d');
            this.chart = new window.Chart(ctx, this.config);
            this.chart.canvas.parentNode.style.height = '100%';
            this.chart.canvas.parentNode.style.width = '100%';
        }).catch(error => {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error loading ChartJS',
                    message: error.message,
                    variant: 'error',
                }),
            );
        });
    }

}

What am I doing wrong?  Thank you
Hello All,

I am facing a below-mentioned error while uploading code from VS code to my developer code. I didn't change anything code I am using as it is given in trailhead.

Error:
=== Deploy Errors
PROJECT PATH                                 ERRORS                                                     
───────────────────────────────────────────  ───────────────────────────────────────────────────────────
force-app\main\default\lwc\detail\detail.js  No MODULE named markup://c:data found : [markup://c:detail]


CODE:
data.js:

export const bikes = [
    {"apiName":"Product__c","childRelationships":{},"fields":{"Category__c":{"displayValue":"Mountain","value":"Mountain"},"CreatedDate":{"displayValue":null,"value":"2018-10-09T03:29:52.000Z"},"Description__c":{"displayValue":null,"value":"A durable e-bike with great looks."},"Id":{"displayValue":null,"value":"a0256000001F1arAAC"},"LastModifiedDate":{"displayValue":null,"value":"2018-10-12T02:57:48.000Z"},"Level__c":{"displayValue":"Racer","value":"Racer"},"MSRP__c":{"displayValue":"$7,800","value":7800},"Material__c":{"displayValue":"Carbon","value":"Carbon"},"Name":{"displayValue":null,"value":"DYNAMO X1"},"Picture_URL__c":{"displayValue":null,"value":"https://s3-us-west-1.amazonaws.com/sfdc-demo/ebikes/dynamox1.jpg"},"SystemModstamp":{"displayValue":null,"value":"2018-10-12T02:57:48.000Z"}},"id":"a0256000001F1arAAC","lastModifiedById":null,"lastModifiedDate":"2018-10-12T02:57:48.000Z","recordTypeInfo":null,"systemModstamp":"2018-10-12T02:57:48.000Z"},
    {"apiName":"Product__c","childRelationships":{},"fields":{"Category__c":{"displayValue":"Mountain","value":"Mountain"},"CreatedDate":{"displayValue":null,"value":"2018-10-09T03:29:52.000Z"},"Description__c":{"displayValue":null,"value":"A durable e-bike with great looks."},"Id":{"displayValue":null,"value":"a0256000001F1atAAC"},"LastModifiedDate":{"displayValue":null,"value":"2018-10-10T17:26:47.000Z"},"Level__c":{"displayValue":"Racer","value":"Racer"},"MSRP__c":{"displayValue":"$6,802","value":6802},"Material__c":{"displayValue":"Aluminum","value":"Aluminum"},"Name":{"displayValue":null,"value":"DYNAMO X2"},"Picture_URL__c":{"displayValue":null,"value":"https://s3-us-west-1.amazonaws.com/sfdc-demo/ebikes/dynamox2.jpg"},"SystemModstamp":{"displayValue":null,"value":"2018-10-10T17:26:47.000Z"}},"id":"a0256000001F1atAAC","lastModifiedById":null,"lastModifiedDate":"2018-10-10T17:26:47.000Z","recordTypeInfo":null,"systemModstamp":"2018-10-10T17:26:47.000Z"},
    {"apiName":"Product__c","childRelationships":{},"fields":{"Category__c":{"displayValue":"Mountain","value":"Mountain"},"CreatedDate":{"displayValue":null,"value":"2018-10-09T03:29:52.000Z"},"Description__c":{"displayValue":null,"value":"A durable e-bike with great looks."},"Id":{"displayValue":null,"value":"a0256000001F1auAAC"},"LastModifiedDate":{"displayValue":null,"value":"2018-10-09T04:37:56.000Z"},"Level__c":{"displayValue":"Enthusiast","value":"Enthusiast"},"MSRP__c":{"displayValue":"$5,601","value":5601},"Material__c":{"displayValue":"Aluminum","value":"Aluminum"},"Name":{"displayValue":null,"value":"DYNAMO X3"},"Picture_URL__c":{"displayValue":null,"value":"https://s3-us-west-1.amazonaws.com/sfdc-demo/ebikes/dynamox3.jpg"},"SystemModstamp":{"displayValue":null,"value":"2018-10-09T04:37:56.000Z"}},"id":"a0256000001F1auAAC","lastModifiedById":null,"lastModifiedDate":"2018-10-09T04:37:56.000Z","recordTypeInfo":null,"systemModstamp":"2018-10-09T04:37:56.000Z"},
    {"apiName":"Product__c","childRelationships":{},"fields":{"Category__c":{"displayValue":"Mountain","value":"Mountain"},"CreatedDate":{"displayValue":null,"value":"2018-10-09T03:29:52.000Z"},"Description__c":{"displayValue":null,"value":"A durable e-bike with great looks."},"Id":{"displayValue":null,"value":"a0256000001F1avAAC"},"LastModifiedDate":{"displayValue":null,"value":"2018-10-09T03:29:52.000Z"},"Level__c":{"displayValue":"Enthusiast","value":"Enthusiast"},"MSRP__c":{"displayValue":"$5,500","value":5500},"Material__c":{"displayValue":"Aluminum","value":"Aluminum"},"Name":{"displayValue":null,"value":"DYNAMO X4"},"Picture_URL__c":{"displayValue":null,"value":"https://s3-us-west-1.amazonaws.com/sfdc-demo/ebikes/dynamox4.jpg"},"SystemModstamp":{"displayValue":null,"value":"2018-10-09T03:29:52.000Z"}},"id":"a0256000001F1avAAC","lastModifiedById":null,"lastModifiedDate":"2018-10-09T03:29:52.000Z","recordTypeInfo":null,"systemModstamp":"2018-10-09T03:29:52.000Z"},
    {"apiName":"Product__c","childRelationships":{},"fields":{"Category__c":{"displayValue":"Mountain","value":"Mountain"},"CreatedDate":{"displayValue":null,"value":"2018-10-09T03:29:52.000Z"},"Description__c":{"displayValue":null,"value":"A durable e-bike with great looks."},"Id":{"displayValue":null,"value":"a0256000001F1azAAC"},"LastModifiedDate":{"displayValue":null,"value":"2018-10-09T03:29:52.000Z"},"Level__c":{"displayValue":"Enthusiast","value":"Enthusiast"},"MSRP__c":{"displayValue":"$4,600","value":4600},"Material__c":{"displayValue":"Aluminum","value":"Aluminum"},"Name":{"displayValue":null,"value":"FUSE X1"},"Picture_URL__c":{"displayValue":null,"value":"https://s3-us-west-1.amazonaws.com/sfdc-demo/ebikes/fusex1.jpg"},"SystemModstamp":{"displayValue":null,"value":"2018-10-09T03:29:52.000Z"}},"id":"a0256000001F1azAAC","lastModifiedById":null,"lastModifiedDate":"2018-10-09T03:29:52.000Z","recordTypeInfo":null,"systemModstamp":"2018-10-09T03:29:52.000Z"},
    {"apiName":"Product__c","childRelationships":{},"fields":{"Category__c":{"displayValue":"Commuter","value":"Commuter"},"CreatedDate":{"displayValue":null,"value":"2018-10-09T03:29:52.000Z"},"Description__c":{"displayValue":null,"value":"A durable e-bike with great looks."},"Id":{"displayValue":null,"value":"a0256000001F1b2AAC"},"LastModifiedDate":{"displayValue":null,"value":"2018-10-09T04:41:56.000Z"},"Level__c":{"displayValue":"Beginner","value":"Beginner"},"MSRP__c":{"displayValue":"$3,200","value":3200},"Material__c":{"displayValue":"Aluminum","value":"Aluminum"},"Name":{"displayValue":null,"value":"ELECTRA X1"},"Picture_URL__c":{"displayValue":null,"value":"https://s3-us-west-1.amazonaws.com/sfdc-demo/ebikes/electrax1.jpg"},"SystemModstamp":{"displayValue":null,"value":"2018-10-09T04:41:56.000Z"}},"id":"a0256000001F1b2AAC","lastModifiedById":null,"lastModifiedDate":"2018-10-09T04:41:56.000Z","recordTypeInfo":null,"systemModstamp":"2018-10-09T04:41:56.000Z"},
    {"apiName":"Product__c","childRelationships":{},"fields":{"Category__c":{"displayValue":"Commuter","value":"Commuter"},"CreatedDate":{"displayValue":null,"value":"2018-10-09T03:29:52.000Z"},"Description__c":{"displayValue":null,"value":"A durable e-bike with great looks."},"Id":{"displayValue":null,"value":"a0256000001F1b3AAC"},"LastModifiedDate":{"displayValue":null,"value":"2018-10-09T03:29:52.000Z"},"Level__c":{"displayValue":"Beginner","value":"Beginner"},"MSRP__c":{"displayValue":"$3,200","value":3200},"Material__c":{"displayValue":"Aluminum","value":"Aluminum"},"Name":{"displayValue":null,"value":"ELECTRA X2"},"Picture_URL__c":{"displayValue":null,"value":"https://s3-us-west-1.amazonaws.com/sfdc-demo/ebikes/electrax2.jpg"},"SystemModstamp":{"displayValue":null,"value":"2018-10-09T03:29:52.000Z"}},"id":"a0256000001F1b3AAC","lastModifiedById":null,"lastModifiedDate":"2018-10-09T03:29:52.000Z","recordTypeInfo":null,"systemModstamp":"2018-10-09T03:29:52.000Z"},
    {"apiName":"Product__c","childRelationships":{},"fields":{"Category__c":{"displayValue":"Commuter","value":"Commuter"},"CreatedDate":{"displayValue":null,"value":"2018-10-09T03:29:52.000Z"},"Description__c":{"displayValue":null,"value":"A durable e-bike with great looks."},"Id":{"displayValue":null,"value":"a0256000001F1b6AAC"},"LastModifiedDate":{"displayValue":null,"value":"2018-10-09T03:29:52.000Z"},"Level__c":{"displayValue":"Beginner","value":"Beginner"},"MSRP__c":{"displayValue":"$2,700","value":2700},"Material__c":{"displayValue":"Aluminum","value":"Aluminum"},"Name":{"displayValue":null,"value":"ELECTRA X3"},"Picture_URL__c":{"displayValue":null,"value":"https://s3-us-west-1.amazonaws.com/sfdc-demo/ebikes/electrax3.jpg"},"SystemModstamp":{"displayValue":null,"value":"2018-10-09T03:29:52.000Z"}},"id":"a0256000001F1b6AAC","lastModifiedById":null,"lastModifiedDate":"2018-10-09T03:29:52.000Z","recordTypeInfo":null,"systemModstamp":"2018-10-09T03:29:52.000Z"},
    {"apiName":"Product__c","childRelationships":{},"fields":{"Category__c":{"displayValue":"Commuter","value":"Commuter"},"CreatedDate":{"displayValue":null,"value":"2018-10-09T03:29:52.000Z"},"Description__c":{"displayValue":null,"value":"A durable e-bike with great looks."},"Id":{"displayValue":null,"value":"a0256000001F1b7AAC"},"LastModifiedDate":{"displayValue":null,"value":"2018-10-09T03:29:52.000Z"},"Level__c":{"displayValue":"Beginner","value":"Beginner"},"MSRP__c":{"displayValue":"$2,700","value":2700},"Material__c":{"displayValue":"Aluminum","value":"Aluminum"},"Name":{"displayValue":null,"value":"ELECTRA X4"},"Picture_URL__c":{"displayValue":null,"value":"https://s3-us-west-1.amazonaws.com/sfdc-demo/ebikes/electrax4.jpg"},"SystemModstamp":{"displayValue":null,"value":"2018-10-09T03:29:52.000Z"}},"id":"a0256000001F1b7AAC","lastModifiedById":null,"lastModifiedDate":"2018-10-09T03:29:52.000Z","recordTypeInfo":null,"systemModstamp":"2018-10-09T03:29:52.000Z"}
];

Detail.js is the file in which I am using data.js
import { LightningElement, api } from 'lwc';
import { bikes } from 'c/data';
export default class Detail extends LightningElement {
    //bikes = bikes;
    product;
    // Private var to track @api productId
    _productId = undefined;
    // Use set and get to process the value every time it's
    // requested while switching between products
    set productId(value) {
        this._productId = value;
        this.product = bikes.find(bike => bike.fields.Id.value === value);
    }
    
    // getter for productId
    @api get productId(){
        return this._productId;
    }
}


Could you please help me why I am getting this error. Even if I remove import { bikes } from 'c/data'; this line it works fine but I don't know why it's not working with that.

Please guide me.

Thanks,
Arpit
 
Hello,
I'm quite new to developing in SalesForce. I'm a developer for many years but never used SalesForce until now.
What I want to know if it is possible to write my own custom javascript function at page load of Account Lead or Opportunity. Is it possible? I want to change some UI with jQuery and add some JS function. My company use Lighting.
Any help is much appreciated
I was trying to create a LWC component and keep it in lightning record page and see the details of the record. But the component is not showing the data.

Can anyone help me with this?

Below are all the details:

Apex Controller:
public with sharing class caseDetailsContollerLWC {
    @AuraEnabled(cacheable=true)
    public static list<case> caseDetails(Id recordId){
        return [select id,casenumber,status,priority,subject,description from case where Id=:recordId];
        //return c;
    }
    }

LWC JS:
import { LightningElement,api,wire } from 'lwc';
import SUBJECT from '@salesforce/schema/Case.subject';
import DESCRIPTION from '@salesforce/schema/Case.description';
import CASENUMBER from '@salesforce/schema/Case.casenumber';
import STATUS from '@salesforce/schema/Case.status';
import PRIORITY from '@salesforce/schema/Case.priority';
const fields=['subject','description','casenumber','status','priority'];
import caseDetails from  '@salesforce/apex/caseDetailsContollerLWC.caseDetails'
export default class caseDetailsLWC extends LightningElement {
@api recordId;
@wire(caseDetails,{recordId:'$recordId',fields})
caseDetails({ error, data }) {
    if (data) {
        this.data  = data;
        this.error = undefined;
    } else if (error) {
        this.error = error;
        this.data  = undefined;
    }
}
}

LWC HTML:
<!--
@File Name          : caseDetailsLWC.html
@Description        : 
@Author             : ChangeMeIn@UserSettingsUnder.SFDoc
@Group              : 
@Last Modified By   : ChangeMeIn@UserSettingsUnder.SFDoc
@Last Modified On   : 3/2/2020, 10:52:24 PM
@Modification Log   : 
Ver       Date            Author                Modification
1.0    3/2/2020   ChangeMeIn@UserSettingsUnder.SFDoc     Initial Version
-->
<template>
    <div class="slds-m-around_medium">
        <template if:true={caseDetails.data}>
            <template for:each={caseDetails.data} for:item="content">
                <p key={content.Id}>{content.Id}</p>
                <p key={content.subject}>{content.subject}</p>
                <p key={content.description}>{content.description}</p>
                <p key={content.priority}>{content.priority}</p>
                <p key={content.casenumber}>{content.casenumber}</p>
               
            </template>
        </template>
        <template if:true={caseDetails.error}>
            No data
        </template>
    </div>
    
    </template>

LWC Meta XML:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="customSearch">
    <apiVersion>46.0</apiVersion>
    <isExposed>true</isExposed>
     <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>
 
  • March 04, 2020
  • Like
  • 0